uni-app之兄弟组件之间的通讯(事件总线)
uni-app之兄弟组件之间的通讯(事件总线)
·
兄弟组件之间的通讯可以通过事件总线和将数据写在全局两种方法,这里只讲事件总线这一种。
son1和son2是兄弟组件,father是父组件
son2通过按钮点击事件中的uni-$emit()将数据传递给son1,son1需要通过uni-$on()注册一个事件接收son2传过来的数据;通过father组件将毫无关系的son1和son2联系起来
代码如下:
son2:
<button type="default" @click="eventBus">兄弟传参1</button>
eventBus(){
uni.$emit('update',{msg:'页面更新'})
},
son1:
uni.$on("update",(data)=>{
console.log('监听到事件来自update,携带参数msg为:'+data.msg);
this.msg = data.msg
}),
// 另一种写法
uni.$on('update',this.update)
father:
<template>
<view>
<son1></son1>
<son2></son2>
</view>
</template>
<script>
import son1 from "../../components/son1/son1.vue"
import son2 from "../../components/son2/son2.vue"
export default {
components:{
son1,
son2
}
}
</script>
更多推荐
已为社区贡献1条内容
所有评论(0)