Vuejs 2: send event from component to parent
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/
For future references, custom events name can not be camelCased.
Use this.$emit('send_event', 'bye')
instead of this.$emit('sendEvent', 'bye')
https://github.com/vuejs/vue/issues/4044
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