1、安装
npm install vue-bus --save
2、注册
在main.js中注册
import Vue from 'vue';
import VueBus from 'vue-bus';//中央事件总线
...
Vue.use(VueBus);
…
3、使用
A页面传递给B也页面:
A页面中,触发了一个叫toBPage的事件,并传递了参数’hello world!’
methods: {
toBPage(){
this.$bus.emit('bPage', 'hello world!');
},
}
B页面中,this.$bus.on监听了bPage并传入了回调函数this.getBPage,该回调函数的参数就是传递过来的数据
created: function () {
this.$bus.on('bPage', this.getBPage);
},
beforeDestroy() {
this.$bus.off('bPage', this.getBPage);
},
methods: {
getBPage(item){
console.log(item);//item就是传递过来的数据
},
}
离开该页面时就无需再监听了,所以要销毁该监听事件,this.$bus.off就是销毁该监听事件