Vue component communication—$bus
$bus: One of vue component communication implementation
Install vue-bus
npm i vue-bus -S
Mount vue-bus to the vue instance in the entry file
import Vue from 'vue'
import VueBus from 'vue-bus'
Vue.use(VueBus)
In component A:
methods: {
getFooterItem(val) {
// val是参数,使用$bus将toItem定义为全局方法 默认参数为val
this.$bus.$emit('toItem', val)
}
In component B:
mounted() {
this.$bus.$on('toItem', (data) => {
// 在生命周期mounted中监听toItem,只要A组件触发了$bus,在B组件中就可以监听的到,data为传来的val值
console.log(data)
})
}