通过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)
})
}
运行结果: