javascript - Vue.js 全局事件不起作用

标签 javascript vue.js

我有

<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/

相关文章:

javascript - 在 Angular 中显示 highcharts 网络图中每个点的工具提示

javascript - 循环总是结束,即使有 setTimeout

javascript - 使用 javascript 删除部分文本

css - 如何在 Vue.js 中使用模式和粘性导航栏修复 z-index?

javascript - Vuex 商店不更新状态

javascript - YouTube 数据 api - 将视频上传到一个 channel

javascript - 加载排序图片

css - 在 VueJS 中导入带有字体的 CSS 文件

javascript - 如何在 VueJS Mixin 中返回值

javascript - 为什么 Vue.js/Axios 不渲染我定义的数据?