Vue 兄弟或父子组件传值的一种方法,通过Vue的$emit发送事件,$on接收事件

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/csl125/article/details/83505961

通过Vue的$emit发送自定义事件,在需要使用的组件中接收

$emit

$on

(0)创建文件 eventBus.js

import Vue from 'vue'
const eventBus = new Vue()

export { eventBus }

(1) 组件一中,在事件中触发 eventBus.$emit('buy-number',this.inputNum)     

//示例:在Vuewatch 中监听本页面的input的value,然后传值给另一个组件
 watch: {
    inputNum () {
      this.$emit('on-change',this.inputNum);
       eventBus.$emit('buy-number',this.inputNum)
    }
  },

(2)组件二中,事件捕获 使用  

//示例:在mounted中一直获取
mounted () {
    eventBus.$on('buy-number', (Num) => {
      console.log('choose传值', Num)
    })
  }

运行结果:

猜你喜欢

转载自blog.csdn.net/csl125/article/details/83505961
今日推荐