场景 :
1、父组件 fateher 、 子组件 send 、 子组件 appect
2、父组件 分别引入 两个子组件,将 send组件 数据 发送给 appect 组件
操作如下:
1、在 utils 文件中 ,创建 eventbus.js 文件 // 首先创建 eventBus 文件
2、在 send 组件
import bus from ‘@/utils/enventBus.js’ .// 引入 enventBus 文件
<button @click="handle"></button> // 点击按钮 触发 handle 事件
data() {
return {
msg: '玉骨遥' // 定义要发送的数据
}
}
methods: {
handle() { // 定义通过按钮触发的的事件
bus.$emit('sendData',this.msg) // 通过 bus. $emit 方法 去触发 sendData 事件 并将数据传递过去
}
}
3、在 accept 组件:
import bus from '@/utils/eventBus.js' // 引入 enventBus 文件
<div>{{ accpetData }}</div> // 渲染 传递过来的数据
data() {
return {
accpetData: ‘ ’ 接受 传递过来的数据 定义变量
}
}
created() {
bus.$on('sendData', (val) => { // 通过 eventBus 实例上 $on 方法 监听 sendData事件 并将 数据 接受过来 并赋值
this.accpetData = val
})
}