vue中事件总线bus的用法
-
./util/Bus.js
import Bus from 'vue'; let install = function (Vue) { // 设置eventBus Vue.prototype.bus = new Bus(); } export default { install };
- 安装:
npm install vue-bus
在main.js 中引入vuebus:
-
1234
import
Vue from
'vue'
;
import
VueBus from
'vue-bus'
;
Vue.use(VueBus);
在组件中使用
触发事件:
this.$bus.emit("事件名",值)应对事件:mounted:function(){this.$bus.on("事件名",function(值){
});},destroyed:function(){this.$bus.off("事件名");}this.$bus.emit ==> 触发this.$bus.on ==> 接収this.$bus.off ==> 清除注意:接收后要清除事件,不然会造成不必要的后果!!!