【vue2】父子组件传值:子组件props更新,父组件同步更新

场景:父组件给子组件传值list,子组件中list更新后,父组件中需要感应到list的更新

方法一:使用 .sync 修饰符(Vue 2.3.0+ 引入,Vue 3 中作为建议的替代方案)

  • 只传一个值
// 父组件
<template>
	<checkbox :list-arr.sync="list" />
</template>

<script>
export default {
	data() {
		return {
			list: [],
		}
	}
}
</script>
// 子组件checkbox.vue
<template>
	...
</template>

<script>
export default {
	props: {
		listArr: {
			type: Array,
			default: () => [],
		},
	},
	methods: {
		change(newvalue) {
			// 在更新listArr后的使用$emit更新父组件的list
			this.$emit('update:listArr', newvalue)
		}
	}
}
</script>

这样写的好处是改变了传统的子组件给父组件$emit值,父组件中还需定义一个函数接收

  • 传多个值且需要同步更新的写法
// 父组件
<template>
	<checkbox 
		:value="value"
		:listArr="list"
		@update:value="value= $event"
		@update:list="list = $event"
	/>
</template>


<script>
export default {
	data() {
		return {
			list: [],
			value: [],
		}
	}
}
</script>
// 子组件checkbox.vue
<template>
	...
</template>

<script>
export default {
	props: {
		listArr: {
			type: Array,
			default: () => [],
		},
		value: {
			type: Array,
			default: () => [],
		},
	},
	methods: {
		change(newvalue) {
			// 在更新listArr后的使用$emit更新父组件的list
			this.$emit('update:listArr', newvalue)
			this.$emit('update:value', newvalue)
		}
	}
}
</script>

方法二:使用 v-model(对于自定义组件,在 Vue 2.2.0+ 中)

// 父组件
<template>
	<checkbox v-model="value" />
</template>

<script>
export default {
	data() {
		return {
			value: [],
		}
	}
}
</script>
// 子组件checkbox.vue
<template>
	...
</template>

<script>
export default {
	model: {  
	    prop: 'value',  
	    event: 'change'  
	  },
	methods: {
		updateValue(newvalue) {
			// 在更新listArr后的使用$emit更新父组件的list
			this.$emit('change', newvalue)
		}
	}
}
</script>

这种我没试过,先记录

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值