vue组件通信-EventBus常用于跨组件通信时使用
两个组件的关系非常的复杂,通过父子组件通讯是非常麻烦的。这时候可以使用通用的组件通讯方案:事件总线(event-bus)
// 1. 创建事件总线 main.js
const bus = new Vue()
// 把bus挂载到了Vue的原型上, 保证所有的组件都能通过 this.$bus访问到事件总线
Vue.prototype.$bus = bus
// 2. 订阅事件 - 接收值
this.$bus.$on('事件名', 事件回调函数)
this.$bus.$on('send', msg => {
})
// 1. 在created中订阅
// 2. 回调函数需要写成箭头函数
// 3. 发布事件 - 传递值
this.$bus.$emit('事件名', 额外参数)
this.$bus.$emit('send', 'hello')
- main.js - 定义事件总线bus对象
const bus = new Vue()
Vue.prototype.$bus = bus
- App.vue - 注册事件 - 等待接收的值
mounted(){
this.$bus.$on("send", (index, price)=>{
let newPrice = this.list[index].proprice;
newPrice > 1 && (newPrice = this.list[index].proprice - price)
this.list[index].proprice = parseFloat(newPrice.toFixed(2));
})
}
- 调用$bus上的send方法
<script>
export default {
props: ['index', 'title', 'price', 'info'], // 声明属性, 等待接收外部传入的值
methods: {
kanFn(){
this.$bus.$emit('send', this.index, 1) // 触发
}
}
}
</script>
总结: main.js注册空的Vue对象, 只负责$on注册事件, e m i t 触 发 事 件 , 一 定 要 确 保 emit触发事件, 一定要确保 emit触发事件,一定要确保on先执行