非父子組件(例如兄弟組件)之間傳值的方式,可以用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就是銷毀該監聽事件
