You need to $emit
on the view model you want to receive your $emit
, use a bus
or use https://vuex.vuejs.org/.
Emitting to parent directly
The easiest way, is to simply $emit
from the child directly to the parent component:
this.$parent.$emit('ChangeView', e.target.dataset.section);
This is OK, but if you have a long chain of components you need to $emit
to each $parent
in the chain.
Emiting via an Event Bus
You can use Vue to create a global event bus very simply. You create an instance of Vue in your main component, then all other components in your application can emit
events to it, and use on
to react to those events.
var bus = new Vue({});
var vm = new Vue({
methods: {
changeView() {
bus.$emit('ChangeView', e.target.dataset.section);
}
});
It is also possible to emit to $root
but this isn't recommended. However, if your app
does get quite complex you may want to consider using Vues own state management system, vuex, instead.
Listening for events
You can listen for the $emit
in the viewmodel using $on
and listening for the specific event:
var vm = new Vue({
created() {
this.$on('ChangeView', section => {
console.log(section);
});
}
);
This would also be similar is you were using the bus, but you would just reference the bus instead:
bus.$on('ChangeView, ...);
And you may also use it directly in your html using v-on
:
<div v-on:ChangeView="doSomething"></div>
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…