Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vuejs 2: send event from component to parent

I have this code:

html

<div id="app">   {{text}}   <my-component></my-component> </div> 

js

Vue.component('my-component', {   template: '<button @click="click">Click me</button>',   methods: {     click() {         this.$emit('send', 'bye')     }   } })  new Vue({   el: "#app",   data: {     text: "hello"   },   created() {     this.$on('send', (text) => {         this.text = text;     })   } }) 

working example: https://jsfiddle.net/rjurado/y4yf6nve/

why event send does not work?

like image 213
drinor Avatar asked Feb 10 '17 09:02

drinor


People also ask

How do you call parent method from child component in Vue?

To call parent method with component with Vue. js, we can get the parent component's method from the $parent property. to define the child component with Vue. component .


2 Answers

Parent components can listen directly to events emitted from child components using v-on.

html

<div id="app">   {{text}}   <my-component v-on:send="sendText"></my-component> </div> 

js

Vue.component('my-component', {   template: '<button @click="click">Click me</button>',   methods: {     click() {       this.$emit('send', 'bye')     }   } })  new Vue({   el: "#app",   data: {     text: "hello"   },   methods: {     sendText(text) {       alert(text)     }   } }) 

Working example: https://jsfiddle.net/y4yf6nve/2/

like image 114
smek Avatar answered Sep 25 '22 21:09

smek


this.$emit only refer to Vue Components. You need to use root instance property to communicate with components from root instance. So basically add root to events:

this.$root.$emit('send', 'bye')  this.$root.$on('send', (text) => {       this.text = text;   }) 

Working example: jsFiddle

Vue.js central event bus

Even better approach is to have central event bus: docs

var bus = new Vue();  Vue.component('my-component', {   template: '<button @click="click">Click me</button>',   methods: {     click() {         bus.$emit('send', 'bye')     }   } })  new Vue({   el: "#app",   data: {     text: "hello"   },   created() {     bus.$on('send', (text) => {         this.text = text;     })   } }) 

Working example: jsFiddle

like image 28
t_dom93 Avatar answered Sep 23 '22 21:09

t_dom93