Table of Contents
Vue Top 20 Artists
{{artist.name}}
{{header}}
{{artist.name}} from {{artist.country}}
Home Web Front-end Vue.js How to use event emitters to modify component data in Vue.js

How to use event emitters to modify component data in Vue.js

Sep 30, 2020 pm 05:51 PM
vue.js

How to use event emitters to modify component data in Vue.js

This article will introduce you how to use event emitters to pass data and its state from child components to its parent component in vue.js. This article is suitable for developers of all stages, including beginners.

Before you start...

We can use props in Vue.js to pass data to child components See in the article In Vue Method in .js to pass data from parent component to child component.

Before reading this article, you should have the following points:

node.js 10.x and above has been installed. You can verify this by running the following command in Terminal/Command Prompt:

1

node -v

Copy after login

  • Code Editor - Visual Studio recommended

  • The latest version of Vue, installed globally on your machine

  • Vue CLI 3.0 is installed on your machine. To do this, first uninstall the old CLI version:

  • 1

    npm uninstall -g vue-cli

    Copy after login
Then, install a new one:

1

npm install -g @vue/cli

Copy after login

  • Download one here

    Vue Getting Started Project

  • Unzip the downloaded project

  • Navigate to the unzipped file and run the following command to Keep all dependencies up to date:

  • 1

    npm install

    Copy after login

Passing data through components

In order to pass data values ​​from the application Parent components in components (such as app.vue) are passed to child components (such as nested components), and Vue.js provides us with a platform called props.

Props can be called custom properties that you can register on a component that allows you to define data in the parent component, assign a value to it, and then pass the value to a prop property that can be Referenced in child components.

This article will show you the flip side of this process. In order to pass and update the data values ​​in the parent component from the child component so that all other nested components will also be updated, we use the emit construct to handle event emission and data updates.

Example:

#You will go through the following process: emitting events from child components, setting up listening parent components to pass from child components data, and finally update the data value.

If you have followed this article from the beginning, you will download and open the

starter project in vs code. This project is complete with complete code as of this article.

The reason for making this a starter project is so you can try out the prop concept before introducing the reversal process.

Start

In that folder you will find two sub-components:

test.vue and test2.vue, its parent component is the app.vue file. We will use the headers of the two child components to illustrate this event emitting method. Your Test.vue file should look like this:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

<template>

  <div>

    <h1 id="Vue-nbsp-Top-nbsp-nbsp-Artists">Vue Top 20 Artists</h1>

    <ul>

      <li v-for="(artist, x) in artists" :key="x">

        <h3 id="artist-name">{{artist.name}}</h3>

      </li>

    </ul>

  </div>

</template>

<script>

export default {

  name: &#39;Test&#39;,

  props: {

    artists: {

      type: Array

    }

  }

}

</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->

<style scoped>

li{

    height: 40px;

    width: 100%;

    padding: 15px;

    border: 1px solid saddlebrown;

    display: flex;

    justify-content: center;

    align-items: center;

  }

a {

  color: #42b983;

}

</style>

Copy after login

To have the headers receive headers from the implicit definition in the data properties section, create the data section and add the definition, then in Add interpolation symbols to the template as follows:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

<template>

  <div>

    <h1 id="header">{{header}}</h1>

    <ul>

      <li v-for="(artist, x) in artists" :key="x">

        <h3 id="artist-name">{{artist.name}}</h3>

      </li>

    </ul>

  </div>

</template>

<script>

export default {

  name: &#39;Test&#39;,

  props: {

    artists: {

      type: Array

    }

  },

  data() {

    return {

     header: &#39;Vue Top Artists&#39;

    }

  }

}

</script>

Copy after login

If you run the application, you will get exactly the same interface as when you started. The next step is to change this defined property on

click.

Toggle Title

To toggle the title you must add an event listener to the title when clicked and specify that the containing A function for the logic that occurs when clicked.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

<template>

  <div>

    <h1 id="header">{{header}}</h1>

    <ul>

      <li v-for="(artist, x) in artists" :key="x">

        <h3 id="artist-name">{{artist.name}}</h3>

      </li>

    </ul>

  </div>

</template>

<script>

export default {

  name: &#39;Test&#39;,

  props: {

    artists: {

      type: Array

    }

  },

  data() {

    return {

     header: &#39;Vue Top Artists&#39;

    }

  },

  methods: {

    callingFunction(){

      this.header = "You clicked on header 1";

    }

  }

}

</script>

Copy after login

Now your title changes to the string inside the calling function on click.

How to use event emitters to modify component data in Vue.js

Set up the emitter

At this stage you want to pass the same behavior to the parent component so that when clicked, each title nested in the parent component will change.

To do this, you will create an emitter that will emit an event in the child component that the parent component can listen to and respond to (this is the same logic as the component's event listener).

Change the script part in the test. vue file to the following code block:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

<script>

export default {

  name: &#39;Test&#39;,

  props: {

    artists: {

      type: Array

    },

    header: {

      type: String

    }

  },

  data() {

    return {

      // header: &#39;Vue Top Artists&#39;

    }

  },

  methods: {

    callingFunction(){

      // this.header = "You clicked on header 1"

      this.$emit(&#39;toggle&#39;, &#39;You clicked header 1&#39;);

    }

  }

}

</script>

Copy after login

Here, define the data type expected by the header as prop. Then, within that method, there is a generate statement that tells Vue to emit an event when it switches (just like other events, such as a click event) and passes the string as a parameter. That's all there is to setting up an event that will be listened to in another component.

Listen for emitted events

Now, the next thing to do after creating the event is to listen for and respond to it. Copy this code block into your app.vue file:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

<template>

  <div id="app">

    <img src="/static/imghw/default1.png"  data-src="./assets/logo.png"  class="lazy"  alt="Vue logo" >

    <Test v-bind:header="header" v-on:toggle="toggleHeader($event)" />

    <Test v-bind:artists="artists" />

    <test2 v-bind:header="header"/>

    <test2 v-bind:artists="artists" />

  </div>

</template>

<script>

import Test from &#39;./components/Test.vue&#39;

import Test2 from &#39;./components/Test2&#39;

export default {

  name: &#39;app&#39;,

  components: {

    Test, Test2

  },

  data (){

    return {

      artists: [

       {name: &#39;Davido&#39;, genre: &#39;afrobeats&#39;, country: &#39;Nigeria&#39;},

       {name: &#39;Burna Boy&#39;, genre: &#39;afrobeats&#39;, country: &#39;Nigeria&#39;},

       {name: &#39;AKA&#39;, genre: &#39;hiphop&#39;, country: &#39;South-Africa&#39;}

      ],

      header: &#39;Vue Top Artists&#39;

    }

  },

  methods: {

    toggleHeader(x){

      this.header = x;

    }

  }

}

</script>

<style>

#app {

  font-family: &#39;Avenir&#39;, Helvetica, Arial, sans-serif;

  -webkit-font-smoothing: antialiased;

  -moz-osx-font-smoothing: grayscale;

  text-align: center;

  color: #2c3e50;

  margin-top: 60px;

}

</style>

Copy after login

在模板部分,您可以看到第一个组件test上有两个vue指令。第一个是v-bind,它将initial header属性绑定到artists数组下的数据对象中的隐式定义;初始化时,将显示字符串vue top artists

第二个指令是v-on,它用于监听事件;要监听的事件是toggle(记住,您已经在测试组件中定义了它),它的调用函数是toggleheader。此函数已创建,子组件中的字符串将通过$event参数传递到此处显示。

含义

这会将数据通过发射器传递到父组件,因此由于其他组件嵌套在父组件中,因此每个嵌套组件中的数据都会重新呈现和更新。进入test2.vue文件并将此代码块复制到其中:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

<template>

  <div>

    <h1 id="header">{{header}}</h1>

    <ul>

      <li v-for="(artist, x) in artists" :key="x">

      <h3 id="artist-name-nbsp-from-nbsp-artist-country">{{artist.name}} from {{artist.country}}</h3>

      </li>

    </ul>

  </div>

</template>

<script>

export default {

  name: &#39;Test2&#39;,

  props: {

    artists: {

      type: Array

    },

    header: {

      type: String

    }

  }

}

</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->

<style scoped>

li{

    height: 40px;

    width: 100%;

    padding: 15px;

    border: 1px solid saddlebrown;

    display: flex;

    justify-content: center;

    align-items: center;

  }

a {

  color: #42b983;

}

</style>

Copy after login

这里,数据插值被设置并指定为道具对象中的一个字符串。在你的开发服务器上运行应用程序:

1

npm run serve

Copy after login

How to use event emitters to modify component data in Vue.js

可以看到,一旦事件在父组件中被响应,所有组件都会更新它们的报头,即使仅在一个子组件中指定了定义。

您可以在github上找到本教程的完整代码。

结论

您可以看到在Vue中使用事件和发射器的另一个有趣的方面:您现在可以在一个组件中创建事件,并在另一个组件中监听它并对它作出反应。

相关推荐:

2020年前端vue面试题大汇总(附答案)

vue教程推荐:2020最新的5个vue.js视频教程精选

更多编程相关知识,请访问:编程入门!!

The above is the detailed content of How to use event emitters to modify component data in Vue.js. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

In-depth discussion of how vite parses .env files In-depth discussion of how vite parses .env files Jan 24, 2023 am 05:30 AM

When using the Vue framework to develop front-end projects, we will deploy multiple environments when deploying. Often the interface domain names called by development, testing and online environments are different. How can we make the distinction? That is using environment variables and patterns.

Detailed graphic explanation of how to integrate the Ace code editor in a Vue project Detailed graphic explanation of how to integrate the Ace code editor in a Vue project Apr 24, 2023 am 10:52 AM

Ace is an embeddable code editor written in JavaScript. It matches the functionality and performance of native editors like Sublime, Vim, and TextMate. It can be easily embedded into any web page and JavaScript application. Ace is maintained as the main editor for the Cloud9 IDE and is the successor to the Mozilla Skywriter (Bespin) project.

What is the difference between componentization and modularization in vue What is the difference between componentization and modularization in vue Dec 15, 2022 pm 12:54 PM

The difference between componentization and modularization: Modularization is divided from the perspective of code logic; it facilitates code layered development and ensures that the functions of each functional module are consistent. Componentization is planning from the perspective of UI interface; componentization of the front end facilitates the reuse of UI components.

Explore how to write unit tests in Vue3 Explore how to write unit tests in Vue3 Apr 25, 2023 pm 07:41 PM

Vue.js has become a very popular framework in front-end development today. As Vue.js continues to evolve, unit testing is becoming more and more important. Today we’ll explore how to write unit tests in Vue.js 3 and provide some best practices and common problems and solutions.

Let's talk in depth about reactive() in vue3 Let's talk in depth about reactive() in vue3 Jan 06, 2023 pm 09:21 PM

Foreword: In the development of vue3, reactive provides a method to implement responsive data. This is a frequently used API in daily development. In this article, the author will explore its internal operating mechanism.

A simple comparison of JSX syntax and template syntax in Vue (analysis of advantages and disadvantages) A simple comparison of JSX syntax and template syntax in Vue (analysis of advantages and disadvantages) Mar 23, 2023 pm 07:53 PM

In Vue.js, developers can use two different syntaxes to create user interfaces: JSX syntax and template syntax. Both syntaxes have their own advantages and disadvantages. Let’s discuss their differences, advantages and disadvantages.

How to query the current vue version How to query the current vue version Dec 19, 2022 pm 04:55 PM

There are two ways to query the current Vue version: 1. In the cmd console, execute the "npm list vue" command to query the version. The output result is the version number information of Vue; 2. Find and open the package.json file in the project and search You can see the version information of vue in the "dependencies" item.

A brief analysis of how to handle exceptions in Vue3 dynamic components A brief analysis of how to handle exceptions in Vue3 dynamic components Dec 02, 2022 pm 09:11 PM

How to handle exceptions in Vue3 dynamic components? The following article will talk about Vue3 dynamic component exception handling methods. I hope it will be helpful to everyone!

See all articles