组件间传值的情况:

  • 子组件→父组件
  • 父组件→子组件
  • 普通组件→普通组件

1、父组件→子组件

father.vue

<template>
	<view>
		<view>这是父组件</view>
		<son :title='title' :content='content'></son>
	</view>
</template>

<script>
	import son from './son.vue'
	export default {
		data() {
			return {
				title: '这是标题',
				content: '这是内容'
			}
		},
		components:{
			son
		}
	}
</script>

son.vue

<template>
	<view class="box">
		<view>这是子组件</view>
		<text>父组件传来的参数:{{title}} ~~ {{content}}</text>
	</view>
</template>

<script>
	export default {
		props:['title', 'content']
	}
</script>

<style>
	.box{
		color: #DD524D;
	}
</style>

在这里插入图片描述

2、子组件→父组件

son.vue

<template>
	<view class="box">
		<view>这是子组件</view>
		<!-- 向父组件传值 -->
		<button @click="toFather" type="warn" size="mini">点击向父组件传值</button>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				text: 'son给father的内容'
			}
		},
		methods:{
			toFather() {
				this.$emit('sonEven', this.text)
			}
		}
	}
</script>

<style>
	.box{
		color: #DD524D;
	}
</style>

father.vue

<template>
	<view>
		<view>这是父组件</view>
		<son @sonEven='getSonText'></son>
		<text style="size: 20rpx;color: #007AFF;">{{fromSon}}</text>
	</view>
</template>

<script>
	import son from './son.vue'
	export default {
		data() {
			return {
				fromSon: ''
			}
		},
		methods:{
			getSonText(pram) {
				this.fromSon = pram
			}
		},
		components:{
			son
		}
	}
</script>

在这里插入图片描述

在这里插入图片描述

3、兄弟组件传值

  • uni.$emit、 uni.$on 、 uni.$once 、uni.$off 触发的事件都是 App 全局级别的,跨任意组件,页面,nvue,vue 等
  • 使用时,注意及时销毁事件监听,比如,页面 onLoad 里边 uni.$on 注册监听,onUnload 里边 uni.$off 移除,或者一次性的事件,直接使用 uni.$once 监听

在b.vue中引入a.vue

a.vue

<template>
	<view class="box">
		<view>这是a组件</view>
		<button type="warn" @click="sendToB">a向b传值</button>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				msg: '这是a向b传送的内容'
			}
		},
		methods:{
			sendToB() {
				uni.$emit('aEven', this.msg)
			}
		}
	}
</script>

<style>
	.box{
		background-color: #DB7093;
		border: 1px solid #DB7093;border-radius: 10rpx;
		width: 50%;height: 50rpx;
	}
</style>

b.vue

<template>
	<view>
		<view class="b">这是b组件</view>
		<A></A>
	</view>
</template>

<script>
	import A from './a.vue'
	export default {
		components:{
			A
		},
		created() {
			// 监听
			uni.$on('aEven', data=>{
				console.log('a组件传来的数据:', data)
			})
		}
	}
</script>

<style>
	.b{
		background-color: #5F9EA0;
		border: 1px solid #5F9EA0;border-radius: 10rpx;
		width: 90%;height: 100rpx;
	}
</style>

在这里插入图片描述

Logo

前往低代码交流专区

更多推荐