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?
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 .
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/
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With