UNI-APP 中 子组件和父组件之间的传参, a组件修改b组件中的数据,组件之间的通讯方式

一、子组件和父组件之间的传参

1、引入子组件页面

import test from '../../components/test.vue'

2、在主页面的components中定义test组件

components: {
			// 定义各个页面的组件,使子页面能在主页面显示
			// test:test,键和值一样,只写test就是了
			//定义组件,<test> </test> 
			test,
			//定义组件,<test-a> </test-a> 
			"test-a":testA,
			//定义组件,<test-b> </test-b> 
			"test-b":testB
		}
<test v-if="flag" :title="title" @myEven='getNum'></test>
这是子组件传过来的参数 {{num}}

3、定义方法

getNum(num) {
				console.log(num)
				this.num = num
			}

4、子组件相关代码

<view id="myView">
		这是一个test组件 {{num}}
		这是父组件传过来的数据 {{title}}
		<button type="default" @click="sendNum">给父组件传值</button>
	</view>
data() {
			return {
				num: 3,
				intId:null
			};
		},
		
		//接收父组件传过来的参数
		props: ['title'],
		
		methods: {
			sendNum() {
				console.log('给父组件传值')
				this.$emit('myEven',this.num)
			}
		},
二、a组件修改b组件中的数据
1、在主页的components 中定义组件
components: {
			// 定义各个页面的组件,使子页面能在主页面显示
			// test:test,键和值一样,只写test就是了
			//定义组件,<test> </test> 
			test,
			//定义组件,<test-a> </test-a> 
			"test-a":testA,
			//定义组件,<test-b> </test-b> 
			"test-b":testB
		}
2、在主页中引入定义好的组件
import testA from '../../components/a.vue'
import testB from '../../components/b.vue'
3、a组件中的代码如下
<template>
	<view>
		这是a组件:<button type="default" @click='addNum'>修改b组件的数据</button>
	</view>
</template>

<script>
	export default {
		name:"a",
		data() {
			return {
				
			};
		},
		methods: {
			addNum(){
				//获取b组件中的数据
				uni.$emit('updateNum',10)
			}
		}
	}
</script>
4、b组件中的代码如下
<template>
	<view>
		这是b组件的数据: {{num}}
	</view>
</template>

<script>
	export default {
		name:"b",
		data() {
			return {
				num: 0
			};
		},
		//页面初始化就执行给方法
		created() {
			uni.$on('updateNum',num=>{
				this.num+=num
			})
		}
	}
</script>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值