vue组件通信-EventBus

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')
  1. main.js - 定义事件总线bus对象
const bus = new Vue()
Vue.prototype.$bus = bus
  1. 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));
    })
}
  1. 调用$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先执行

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值