uniapp子组件向父组件传值

发布时间:2024年01月04日

子组件向父组件传值

子组件1

<template>
	<view class="content">
		<view v-for="(item,index) in list" :key="index">{{item}}</view>
	</view>
</template>
 
<script>
	export default {
		data() {
			return {
				list: []
			}
		},
		components: {
		},
		onLoad() {},
		created() {
			var data = require('../../static/res.json')
			this.list = data.fruitData
			this.$emit("getChild1",this.list);
		},
		methods: {
		}
	}
</script>
 
<style>
	.content {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}
 
	.logo {
		height: 200upx;
		width: 200upx;
		margin-top: 200upx;
		margin-left: auto;
		margin-right: auto;
		margin-bottom: 50upx;
	}
 
	.text-area {
		display: flex;
		justify-content: center;
	}
 
	.title {
		font-size: 36upx;
		color: #8f8f94;
	}
</style>

子组件2

<template>
	<view class="content">
		<view v-for="(item,index) in list" :key="index">{{item}}</view>
	</view>
</template>
 
<script>
	export default {
		data() {
			return {
				list: []
			}
		},
		components: {
		},
		onLoad() {},
		created() {
			var data = require('../../static/res.json')
			this.list = data.filmData
			this.$emit("getChild2",this.list);
		},
		methods: {
		}
	}
</script>
 
<style>
	.content {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}
 
	.logo {
		height: 200upx;
		width: 200upx;
		margin-top: 200upx;
		margin-left: auto;
		margin-right: auto;
		margin-bottom: 50upx;
	}
 
	.text-area {
		display: flex;
		justify-content: center;
	}
 
	.title {
		font-size: 36upx;
		color: #8f8f94;
	}
</style>

父组件

<template>
	<view class="content">
		<view class="btn-container">
			<button @click="getData(index)" v-for="(item,index) in list" :key="index">{{item}}</button>
		</view>
		<child1 @getChild1 = "getChild1" v-if="current==0"></child1>
		<child2 @getChild2 = "getChild2" v-if="current==1"></child2>
	</view>
</template>
 
<script>
	import child1 from './child1'
	import child2 from './child2'
	
	export default {
		data() {
			return {
				list:[
					'水果',
					'电影'
				],
				current:0
			}
		},
		onLoad() {
 
		},
		components: {
			child1,
			child2
		},
		methods: {
			getData(index){
				this.current = index
			},
			getChild1(e){
				console.log(e)
			},
			getChild2(e){
				console.log(e)
			}
		}
	}
</script>
 
<style>
	.content {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}
	.btn-container{
		display: flex;
		justify-content: space-between;
		align-items: center;
	}
</style>

最后

感觉文章好的话记得点个心心和关注和收藏,有错的地方麻烦指正一下,如果需要转载,请标明出处,多谢!!!

文章来源:https://blog.csdn.net/m0_49714202/article/details/135390738
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。