我有
<component-one></component-one>
<component-two></component-two>
<component-three></component-three>
组件 two
包含组件 three
.
目前我emit
<component-one>
中的一个事件必须捕获 <component-three>
.
在<component-one>
我这样触发事件:
this.$bus.$emit('setSecondBanner', finalBanner);
然后在<component-three>
我是这样理解的:
mounted() {
this.$bus.$on('setSecondBanner', (banner) => {
alert('Caught');
this.banner = banner;
});
},
但事件永远不会是caught
!
我这样定义总线(在我的 core.js 中):
let eventBus = new Vue();
Object.defineProperties(Vue.prototype, {
$bus: {
get: () => { return eventBus; }
}
});
这里可能有什么问题?当我检查 vue-dev-tools
我可以看到事件已触发!
最佳答案
这是 vue1 的工作示例。
Object.defineProperty(Vue.prototype, '$bus', {
get() {
return this.$root.bus;
}
});
Vue.component('third', {
template: `<div> Third : {{ data }} </div>`,
props:['data']
});
Vue.component('second', {
template: `<div>Second component <third :data="data"></third></div>`,
ready() {
this.$bus.$on('setSecondBanner', (event) => {
this.data = event.data;
});
},
data() {
return {
data: 'Defautl value in second'
}
}
});
Vue.component('first', {
template: `<div>{{ data }}</div>`,
ready() {
setInterval(() => {
this.$bus.$emit('setSecondBanner', {
data: 'Bus sending some data : '+new Date(),
});
}, 1000);
},
data() {
return {
data: 'Defautl value in first'
}
}
});
var bus = new Vue({});
new Vue({
el: '#app',
data: {
bus: bus
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/1.0.28/vue.js"></script>
<div id="app">
<second></second>
<first></first>
</div>
关于javascript - Vue.js 全局事件不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47712911/