兄弟组件之间的通讯可以通过事件总线和将数据写在全局两种方法,这里只讲事件总线这一种。

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>

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐