uniapp传值

364 阅读1分钟

父子组件传值

子组件

<template>
	<view class="text">
		<h3>我是子组件test这是父index组件传递过来的参数 :{{title}}</h3>
		<button type="primary"  @click="sendNum">给父组件传值</button>
		
	</view>
</template>

<script>
	export default {
		props:['title'],
		data(){
			return {
				num:2000
				
			}
		},
		methods:{
			sendNum(){
				console.log("给父组件传值")
				this.$emit("myEvent",this.num)
			}
		}
	}
</script>

<style>
</style>

父组件

<template>
	<view class="content">
		<h3   >我是父组件index这是子组件传递过来的参数 :{{num}}</h3>
		<!-- 注意@myEvent = "getNum" 放到test使用的组件上面 -->
		<test @myEvent = "getNum" :title = "title"></test>
		<azhu></azhu>
		<bzhu></bzhu>
	</view>
</template>

<script>
	import test from "../components/test.vue"
	import azhu from "../components/a.vue"
	import bzhu from "../components/b.vue"
	export default {
		
		components:{
			test,
			azhu,
			bzhu
		},
		data() {
			return {
				title: 'Hello',
				num:0,
				zhumsg:''
			}
		},
		onLoad() {
			
		},
		methods: {
			getNum(num){
				console.log(num)
				this.num = num
			}
		}
	}
</script>

<style>
	.content {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}

	.logo {
		height: 200rpx;
		width: 200rpx;
		margin-top: 200rpx;
		margin-left: auto;
		margin-right: auto;
		margin-bottom: 50rpx;
	}

	.text-area {
		display: flex;
		justify-content: center;
	}

	.title {
		font-size: 36rpx;
		color: #8f8f94;
	}
</style>

兄弟组件a和b传值

b:

<template>
	<view class="b">
		<h4>这是b组件:{{num}}</h4>
		<button type="primary" @click="subnum1">修改a</button>
	</view>
</template>

<script>
	export default{
		data(){
			return{
				num:0
			}
		},
		created() {
			uni.$on("xiugaib",(num)=>{
				this.num += num
			})
		},
		methods:{
			subnum1(){
				uni.$emit("xiugaia",20)
			}
		}
	}
</script>

<style>
</style>

a

<template>
	<view class="a">
		<h4>
			这是a组件 {{num1}}
		</h4>
		<button type="primary" @click="addnum">修改b</button>
		
	</view>
</template>

<script>
	export default{
		data(){
			return {
				num1 :100
			}
		},
		methods:{
			addnum(){
				// chufa
				uni.$emit("xiugaib",10)
			}
		},
		created() {
			uni.$on("xiugaia",(num1)=>{
				this.num1 -= num1
			})
		}
	}
</script>

<style>
</style>