文章目录
- 一、实现步骤
- 二、代码示例
作用:非父子组件之间,进行简易消息传递。(复杂场景→ Vuex)
一、实现步骤
-
创建一个都能访问的事件总线 (空Vue实例) → utils/EventBus.js
叫事件总线的原因是因为本质是它俩消息的接受和发送是利用了Vue的事件机制
import Vue from 'vue' const Bus = new Vue() export default Bus
-
A组件(接受方),监听Bus的 $on事件
created () {// B组件通过触发事件传递了参数(发布消息),进而在A组件由于监听了这个消息,进而就会执行回调Bus.$on('sendMsg', (msg) => {this.msg = msg}) }
-
B组件(发送方),触发Bus的$emit事件
Bus.$emit('sendMsg', '这是一个消息')
二、代码示例
EventBus.js
import Vue from 'vue'
const Bus = new Vue()
export default Bus
BaseA.vue(接受方)
<template><div class="base-a">我是A组件(接受方)<p>{{msg}}</p> </div>
</template><script>
import Bus from '../utils/EventBus'
export default {data() {return {msg: '',}},created() {Bus.$on('sendMsg', (msg) => {// console.log(msg)this.msg = msg})},
}
</script><style scoped>
.base-a {width: 200px;height: 200px;border: 3px solid #000;border-radius: 3px;margin: 10px;
}
</style>
BaseB.vue(发送方)
<template><div class="base-b"><div>我是B组件(发布方)</div><button @click="sendMsgFn">发送消息</button></div>
</template><script>
import Bus from '../utils/EventBus'
export default {methods: {sendMsgFn() {Bus.$emit('sendMsg', '今天天气不错,适合旅游')},},
}
</script><style scoped>
.base-b {width: 200px;height: 200px;border: 3px solid #000;border-radius: 3px;margin: 10px;
}
</style>
BaseC.vue(接收方)
<template><div class="base-c">我是C组件(接受方)<p>{{msg}}</p> </div>
</template><script>
import Bus from '../utils/EventBus'
export default {data() {return {msg: '',}},created() {Bus.$on('sendMsg', (msg) => {// console.log(msg)this.msg = msg})},
}
</script><style scoped>
.base-c {width: 200px;height: 200px;border: 3px solid #000;border-radius: 3px;margin: 10px;
}
</style>
App.vue
<template><div class="app"><BaseA></BaseA><BaseB></BaseB><BaseC></BaseC></div>
</template><script>
import BaseA from './components/BaseA.vue'
import BaseB from './components/BaseB.vue'
import BaseC from './components/BaseC.vue'
export default {components:{BaseA,BaseB,BaseC}
}
</script><style></style>