数据总线
数据总线介绍
1.可以实现 《父与子》《子与父》《兄弟组件》《跨组件》 之间通信
(1)定义一个数据总线---> 本质就是一个vue对象
(2)在传输数据组件中 添加一个事件
(3)在(2)定义的事件中 利用 $emit 方法进行传输=======》 参数1:相当于通信协议,参数二: 传输的数据
(4)在接受数据组件中利用 $on 方法接收数据=======》 参数1:通信协议,参数二: 一个函数--> 函数参数是接受的数据。该操作需写在 mounted 钩子 中
(5)然后对接收的数据进行处理。
代码实现
# --------------------------------------html 代码-----------------------------------------
<div id="app" ref="reference">
<p class="p1">我是父组件</p>
<child1 id="child_01"></child1>
<child2 id="child_02"></child2>
</div>
# -----------------------------------JavaScript 代码-----------------------------------------
var dataDus = new Vue() # 1. new一个vue的实例,就是中央事件总线。
Vue.component('child1', {
template: `
<div class="item">
<p>我是子组件1</p>
<button @click="handleClick">点我将数据传给兄弟</button> # 2. 在传输数据组件中 添加一个事件
<input type="text" v-model="myText">
</div>`,
data() {
return {
myText: '',
}
},
methods: {
handleClick() {
dataDus.$emit('communication', this.myText) # 3.在事件中 利用 $emit 方法 参数1:相当于通信协议,参数二: 传输的数据
}
},
})
Vue.component('child2', {
template: `
<div class="item">
<p>我是子组件2</p>
{{myText}}
</div>
`,
data() {
return {
myText: '',
}
},
mounted() {
dataDus.$on('communication', (myText) => { # 4.在接受数据组件中利用 $on 方法 参数1:传输数据方给的通信协议,参数二: 一个函数--> 函数参数是接受的数据。
this.myText = myText # 5.然后对接收的数据进行处理。
})
},
})
全局注册
### ----------- main.js ----------- ###
//创建vm
new Vue({
el:'#app',
render: h => h(App),
# beforeCreate中模板未解析,且this是vm
beforeCreate(){
Vue.prototype.$bus = this # 安装全局事件总线
}
})
### ----------- 01.vue ----------- ###
methods:{
// 触发事件,事件名不能重复
sendName(){
this.$bus.$emit('lufei', this.name);
}
},
### ----------- 02.vue ----------- ###
mounted(){
# 绑定事件
this.$bus.$on('lufei', (data)=>{
console.log('lufei', data);
})
},
# 销毁对应自定义事件, 提高性能。(可选)
beforeDestroy(){
this.$bus.$off('lufei')
}