Vue状态管理Bus的使用
BUS总线
在开发过程中我们经常会遇到两个兄弟组件之间的需要通信的情况,虽然Vue2.X提供了Vuex状态管理模式,但是在简单的应用中,使用Vuex就十分的冗余了,所以使用BUS作为中央事件总线,来实现兄弟件之间的传值。
方法一:
将Bus.js单独抽离出来,Bus.js文件如下:
import Vue from 'vue'
const Bus = new Vue()
export default Bus
组件调用时引入Bus.js
组件ChildOne.vue域ChildTwo.vue为兄弟组件
组件1:ChildOne.vue
<script>
import Bus from './Bus.js'
export default {
name: 'ChildOne',
data () {
return {
... ...
}
},
methods: {
bus () {
Bus.$emit('one', '传值给兄弟组件')
}
}
}
</script>
在该组件中需调用bus()方法。
组件2:ChildTwo.vue,该组件中也需要引入Bus.js
import Bus from './Bus.js'
<script>
export default {
name: 'ChildTwo',
data () {
return {
... ...
}
},
mounted () {
Bus.$on('one', content => {
console.log(content) //传值给兄弟组件
})
}
}
</script>
在钩子函数中接受兄弟组件传过来的值
这种方法使用Bus会有一个潜在的问题,就是经过webpack打包后可能会出现Bus局部作用域的情况,就是引用了两个不同的Bus,导致应用不能正常的进行通信。所以推荐以下方法。
方法二:
将Bus注入到Vue的根对象中,即在main.js中加入如下代码:
const Bus = new Vue()
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
components: { App },
template: '<App/>',
data: {
Bus
}
})
组件1:ChildOne.vue
<script>
export default {
name: 'ChildOne',
data () {
return {
... ...
}
},
methods: {
bus () {
this.$root.Bus.$emit('one', '传值给兄弟组件')
}
}
}
</script>
该组件中仍需调用bus()方法
组件2:ChildTwo.vue
<script>
export default {
name: 'ChildTwo',
data () {
return {
... ...
}
},
mounted () {
this.$root.Bus.$on('one', content => {
console.log(content)
})
}
}
</script>