yangxuanLL

vue-bus中央事件总线

非父子组件(例如兄弟组件)之间传值的方式,可以用vuex,也可以用事件总线,已下是事件总线(vue-bus)的介绍:

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就是销毁该监听事件

posted on 2019-06-21 16:06  yangxuanLL  阅读(4253)  评论(0编辑  收藏  举报

导航