search
HomeWeb Front-endVue.jsHow to use event emitters to modify component data in 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:

node -v

  • 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:

  • npm uninstall -g vue-cli
Then, install a new one:

npm install -g @vue/cli

  • 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:

  • npm install

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:

<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>

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:

<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>

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.

<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>

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:

<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>

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:

<template>
  <div id="app">
    <img src="/static/imghwm/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>

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

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

含义

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

<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>

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

npm run serve

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
This article is reproduced at:logrocket. If there is any infringement, please contact admin@php.cn delete
The Choice of Frameworks: What Drives Netflix's Decisions?The Choice of Frameworks: What Drives Netflix's Decisions?Apr 13, 2025 am 12:05 AM

Netflix mainly considers performance, scalability, development efficiency, ecosystem, technical debt and maintenance costs in framework selection. 1. Performance and scalability: Java and SpringBoot are selected to efficiently process massive data and high concurrent requests. 2. Development efficiency and ecosystem: Use React to improve front-end development efficiency and utilize its rich ecosystem. 3. Technical debt and maintenance costs: Choose Node.js to build microservices to reduce maintenance costs and technical debt.

React, Vue, and the Future of Netflix's FrontendReact, Vue, and the Future of Netflix's FrontendApr 12, 2025 am 12:12 AM

Netflix mainly uses React as the front-end framework, supplemented by Vue for specific functions. 1) React's componentization and virtual DOM improve the performance and development efficiency of Netflix applications. 2) Vue is used in Netflix's internal tools and small projects, and its flexibility and ease of use are key.

Vue.js in the Frontend: Real-World Applications and ExamplesVue.js in the Frontend: Real-World Applications and ExamplesApr 11, 2025 am 12:12 AM

Vue.js is a progressive JavaScript framework suitable for building complex user interfaces. 1) Its core concepts include responsive data, componentization and virtual DOM. 2) In practical applications, it can be demonstrated by building Todo applications and integrating VueRouter. 3) When debugging, it is recommended to use VueDevtools and console.log. 4) Performance optimization can be achieved through v-if/v-show, list rendering optimization, asynchronous loading of components, etc.

Vue.js and React: Understanding the Key DifferencesVue.js and React: Understanding the Key DifferencesApr 10, 2025 am 09:26 AM

Vue.js is suitable for small to medium-sized projects, while React is more suitable for large and complex applications. 1. Vue.js' responsive system automatically updates the DOM through dependency tracking, making it easy to manage data changes. 2.React adopts a one-way data flow, and data flows from the parent component to the child component, providing a clear data flow and an easy-to-debug structure.

Vue.js vs. React: Project-Specific ConsiderationsVue.js vs. React: Project-Specific ConsiderationsApr 09, 2025 am 12:01 AM

Vue.js is suitable for small and medium-sized projects and fast iterations, while React is suitable for large and complex applications. 1) Vue.js is easy to use and is suitable for situations where the team is insufficient or the project scale is small. 2) React has a richer ecosystem and is suitable for projects with high performance and complex functional needs.

How to jump a tag to vueHow to jump a tag to vueApr 08, 2025 am 09:24 AM

The methods to implement the jump of a tag in Vue include: using the a tag in the HTML template to specify the href attribute. Use the router-link component of Vue routing. Use this.$router.push() method in JavaScript. Parameters can be passed through the query parameter and routes are configured in the router options for dynamic jumps.

How to implement component jump for vueHow to implement component jump for vueApr 08, 2025 am 09:21 AM

There are the following methods to implement component jump in Vue: use router-link and <router-view> components to perform hyperlink jump, and specify the :to attribute as the target path. Use the <router-view> component directly to display the currently routed rendered components. Use the router.push() and router.replace() methods for programmatic navigation. The former saves history and the latter replaces the current route without leaving records.

How to jump to the div of vueHow to jump to the div of vueApr 08, 2025 am 09:18 AM

There are two ways to jump div elements in Vue: use Vue Router and add router-link component. Add the @click event listener and call this.$router.push() method to jump.

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use