Vue中关于子组件通过双向绑定时,利用props修改父组件中数据报错问题
- 在官方文档中,不允许子组件直接通过双向绑定,修改props属性中的值,若要修改,则会报错
- 解决方法:
- 因为子组件的props属性绑定的是父组件中的data,当子组件直接通过双向绑定(props)来修改值时,相当于通过该属性直接修改了父组件中的data,该做法是不允许的
- 因此实现双向绑定时,还是需要绑定data属性中的值:即首先将父组件的data值传给子组件中props的属性,然后在子组件中声明data属性,用props属性中的值初始化data中的数据
- 但是此时还是只实现了input输入框改变子组件中的data值,那么如何使父组件中的data值也发生改变呢(即实现通过子组件修改父组件中的数据)?
- 在子组件中直接使用v-model绑定的是子组件中的data,还是无法改变父组件中的data,因此不能直接使用v-model,这里利用v-model的原理
- 分两步:
- 第一步:在子组件使用:value绑定子组件中的data
- 第二步:在子组件中,绑定input事件,在子组件中定义事件,将子组件data中的值通过event.target.value改变,在将改变后的值通过$emit传递给父组件
- 在父组件中定义事件,用父组件中的data来接收子组件中的data,从而实现子组件改变父组件中的data
效果:

代码部分:
<div id="app">
<child-cpn :num1="num1" :num2="num2"
@fchange1="fchange1" @fchange2="fchange2"></child-cpn>
</div>
<template id="childCpn">
<div>
<h4>props:{{num1}}</h4>
<h4>data:{{dnum1}}</h4>
<input type="text" :value="dnum1" @input="change1">
<h4>props:{{num2}}</h4>
<h4>data: {{dnum2}}</h4>
<input type="text" :value="dnum2" @input="change2">
</div>
</template>
<script>
const childCpn = {
template: "#childCpn",
methods: {
},
props: {
num1: Number,
num2: Number
},
data() {
return {
dnum1: this.num1,
dnum2: this.num2
}
},
methods: {
change1(event) {
this.dnum1 = event.target.value;
this.$emit('fchange1', this.dnum1)
},
change2(event) {
this.dnum2 = event.target.value;
this.$emit('fchange2', this.dnum2)
}
}
}
const app = new Vue({
el: "#app",
components: {
childCpn
},
data: {
num1: 1,
num2: 2
},
methods: {
fchange1(data) {
data = parseInt(data);
this.num1 = data;
},
fchange2(data) {
data = parseInt(data);
this.num2 = data;
}
}
})
</script>