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

xiaoxiao2025-04-28  13

通过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) }) }

运行结果:

转载请注明原文地址: https://www.6miu.com/read-5029368.html

最新回复(0)