任意组件通信
在main.js的Vue实例中添加beforeCreate(){ Vue.prototype.$bus = this //安装全局事件总线 }来实现任意组件间通信。
1.找到main.js文件
new Vue({
render: h => h(App),
beforeCreate(){
Vue.prototype.$bus = this //安装全局事件总线
}
}).$mount('#app')
2.传值的组件 使用 this.$bus.$emit()
<template>
<div>
<button @click="passName">点我传名字</button>
</div>
</template>
<script>
export default {
data() {
return {
name: "张三"
}
},
methods: {
passName() {
this.$bus.$emit('passName', this.name) //事件名,要传的值
}
}
}
</script>
3.接收值的组件使用 this.$bus.$on()
<template>
<div>
{{passName}}
</div>
</template>
<script>
export default {
data(){
return {
passName: ""
}
},
mounted(){
this.$bus.$on("passName",(data)=>{
this.passName = data //data就是传过来的值
})
},
//销毁绑定到Vue实例上的事件
beforeDestroy() {
this.$bus.$off("passName")
}
}
</script>