vue双向绑定v-model实现子组件修改数据

风信子 2021-06-25 16:08:50 3023℃

版本说明

Vue 2.6.12

Vue-Cli 4.2.3

需求说明

默认情况下,我们可以使用v-model属性来实现父子组件数据双向绑定。

<input type="text" v-model="value">

这样当父组件数据更新时,子组件的数据也会同步更新。

但是如果我们要在子组件更新数据,并且同步更新父组件数据时,就会报错。

[Vue warn]: Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead, use a data or computed property based on the prop's value. Prop being mutated: "value"

解决方法

我们可以在子组件中使用model属性实现父子组件数据双向绑定修改。

父组件 parent.vue

<template>
  <div class="parent">
    父组件:{{ number }} 
    <button type="button" @click="add">+1</button> 
    <button type="button" @click="minus">-1</button>
	<hr />
	<!-- 子组件数据双向绑定-->
    <child v-model="number"></child>
  </div>
</template>

<script>
	//引入子组件
	import child from "./child.vue";
	export default{
		name: 'Parent',
		components: {
			child
		},
		data() {
			return {
				number: 10
			}
		},
		methods: {
			//父组件数据自增
			add() {
				this.number++;
			},
			//父组件数据自减
			minus() {
				this.number--;
			}
		}
	}
</script>

子组件 child.vue

<template>
  <div class="child">
    子组件:{{ childValue }} 
    <button type="button" @click="add">+1</button> 
    <button type="button" @click="minus">-1</button>
  </div>
</template>

<script>
	export default{
		name: 'Child',
		//接收父组件传来的数据
		props: ['value'],
		data() {
			return {
				//子组件数据保存
				childValue: null
			}
		},
		created() {
			//组件初始化时,将父组件数据保存到子组件数据中
			this.childValue = this.value;
		},
		watch: {
			//监听子组件数据变化
			childValue: function(newVal){
				//更新父组件数据
				this.$emit('change', newVal);
			},
			//监听父组件数据变化
			value: function(newVal){
				//更新子组件数据
				this.childValue = newVal;
			}
		},
		//双向绑定自定义事件属性
		model: {
			prop: 'value',
			event: 'change'
		},
		methods: {
			//子组件数据自增
			add() {
				this.childValue++;
			},
			//子组件数据自减
			minus() {
				this.childValue--;
			}
		}
	}
</script>

最终实现效果图

标签: HTML, JS, Vue

非特殊说明,本博所有文章均为博主原创。