vue中使用Bus

//安装: npm install vue-bus

1
. // app.js var eventBus = { install(Vue,options) { Vue.prototype.$bus = new Vue() } }; Vue.use(eventBus); 2.然后在组件中,可以使用$emit, $on, $off 分别来分发、监听、取消监听事件: methods: { todo: function () { this.$bus.$emit('todoSth', params); //params是传递的参数 //... } } 3.监听的组件: // ... created() { this.$bus.$on('todoSth', function(params){ //获取传递的参数并进行操作 //todo something }) }, // 最好在组件销毁前 // 清除事件监听 beforeDestroy () { this.$bus.$off('todoSth'); }
原文地址:https://www.cnblogs.com/huanhuan55/p/11367526.html