来源:www.jianshu.com/p/4fa3bf211…
参考:segmentfault.com/a/119000001…
0:使用场景
-使用场景:在中小型项目,作为vuex的替代工具。
-现实途径:在组件之中引入一个新的vue实例,分别调用这个实例的事件触发和监听来实现通信和参数传递。
1、main.js全局注册
var EventBus = new Vue();
Object.defineProperties(Vue.prototype, {
$bus: {
get: function () {
return EventBus
}
}
})
2、发送组件:
this.$bus.$emit("updateMessage", this.message)
updateMessage事件可以是字符串、数组、对象等任何格式
如果事件在多页面运用,要在销毁该页面时接触绑定,要不然在其他页面也触发了该页面的事件
beforeDestroy () {
$this.$bus.$off('updateMessage')
}
3、接收组件
this.$bus.$on('updateMessage', function(value) {
console.log(value);
})