六、$bus事件总线的使用
1)配置事件总线
// src/main.js
new Vue({
render: h => h(App),
// 注册路由
router,
store,
// 全局事件总线配置
beforeCreate() {
Vue.prototype.$bus = this
},
}).$mount('#app')
2)使用
- 发送
<!-- src/components/Test/$busTest/EmitTest.vue -->
<template>
<div>
<button @click="handleClick">清空OnTest组件中的message</button>
</div>
</template>
<script>
export default {
name: "EmitTest",
data() {
return {
newMessage: "新的message"
}
},
methods: {
handleClick() {
// 发送不含参数参数
// this.$bus.$emit('$busTest')
// 发送含有参数
this.$bus.$emit('$busTest', this.newMessage)
}
},
}
</script>
<style lang="less" scoped>
</style>
- 接收
<!-- src/components/Test/$busTest/OnTest.vue -->
<template>
<div>
<h1>{{ message }}</h1>
</div>
</template>
<script>
export default {
name: "OnTest",
data() {
return {
message: "事件总线测试",
};
},
mounted () {
// 接受不含参数参数
// this.$bus.$on("$busTest", () => {
// this.message = "不含参数"
// })
// 接受含有参数
this.$bus.$on("$busTest", (newMessage) => {
this.message = newMessage
})
},
};
</script>
<style lang="less" scoped>
</style>