vue组件化通信之父向子传值

vue组件化通信之子向父传值
vue组件化通信之兄弟组件传值

父向子组件传值

常用的方法主要有三种:props、$refs、$children 建议使用前两种

使用props进行传值

parent.vue

	<template>
	<div>
		<childTest :msg='msg'></childTest>
	</div>
</template>

<script>
	import childTest from  './childTest.vue'
	export default {
		components:{
			childTest
		},
		data() {
			return{
				msg: 'my vue'
			}
		}
	}
</script>

childTest.vue

<template>
	<div>
		<h1>{{msg}}</h1>
	</div>
</template>

<script>
	export default {
		props: {
			msg: {
				type: String,
				default: ''//默认值
			}
		}
	}
</script>

使用$refs进行传值

parent.vue

<template>
	<div>
		<childTest ref='child'></childTest>
	</div>
</template>

<script>
	import childTest from './childTest.vue'
	export default {
		components:{
			childTest
		},
		mounted() {
			this.$refs.child.msg = 'my vue rfs'
		}
	}
</script>

childTest.vue

<template>
	<div>
		<h1>{{msg}}</h1>
	</div>
</template>

<script>
	export default {
		data(){
			return{
				msg: ''
			}
		}
	}
</script>

使用$children进行传值

parent.vue

<template>
	<div>
		<childTest></childTest>
	</div>
</template>

<script>
	import childTest from './childTest.vue'
	export default {
		components: {
			childTest
		},
		mounted() {
			/* 
			 当前实例的直接子组件。需要注意 $children 并不保证顺序,也不是响应式的。如果			  你发现自己正在尝试使用 $children 来进行数据绑定,考虑使用一个数组配合 v-for 				 来生成子组件,并且使用 Array 作为真正的来源。
			 */
			this.$children[0].msg = 'my vue $children'
		}
	}
</script>

childTest.vue

<template>
	<div>
		<h1>{{msg}}</h1>
	</div>
</template>

<script>
	export default {
		data(){
			return{
				msg: ''
			}
		}
	}
</script>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值