问题
假设我有一个名为:
注意:所有 vue 组件都已简化以解释我要做什么。
可重用组件.vue
<template>
<div class="input-group input-group-sm">
<input type="text" :value.number="setValue" class="form-control" @input="$emit('update:setValue', $event.target.value)">
<span>
<button @click="incrementCounter()" :disabled="disabled" type="button" class="btn btn-outline-bordercolor btn-number" data-type="plus">
<i class="fa fa-plus gray7"></i>
</button>
</span>
</div>
</template>
<script>
import 'font-awesome/css/font-awesome.css';
export default {
props: {
setValue: {
type: Number,
required: false,
default: 0
}
},
data() {
return {
}
},
methods: {
incrementCounter: function () {
this.setValue += 1;
}
}
}
</script>
然后在父组件中我做这样的事情:
子表单.vue
<div class="row mb-1">
<div class="col-md-6">
Increment Value of Num A
</div>
<div class="col-md-6">
<reuseable-comp :setValue.sync="numA"></reuseable-comp>
</div>
</div>
<script>
import reusableComp from '../reusable-comp'
export default {
components: {
reusableComp
},
props: {
numA: {
type: Number,
required: false,
default: 0
}
},
data() {
return {
}
}
</script>
然后最后
页面布局.vue
<template>
<div>
<subform :numA.sync="data1" />
</div>
</template>
<script>
import subform from '../subform.vue'
export default {
components: {
subform
},
data() {
return {
data1: 0
}
}
}
</script>
问题
那么,如何在 reusable-comp.vue、subform.vue 和 page_layout.vue 之间同步值
我在很多不同的地方使用 reuseable-comp.vue。我在 page_layout.vue 中只使用了几次 subform.vue
我尝试多次使用这种模式。但我似乎无法让它发挥作用。以上给了我一个错误:
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: "numA"
最佳答案
好的,我找到了一个有效的解决方案。
在 subform.vue 中,我们改变:
data() {
return {
numA_data : this.numA
}
}
因此,我们现在可以使用 react 性数据。然后在模板中,我们引用响应式数据而不是 prop:
<reuseable-comp :setValue.sync="numA_data"></reuseable-comp>
然后最后我们添加一个观察者来检查 react 数据是否发生变化,然后发送给父级:
watch: {
numA_data: function(val) {
this.$emit('update:numA', this.numA_data);
}
}
现在从孙子到父的所有值都已同步。
更新(2018 年 4 月 13 日)
我对 reusable-comp.vue 做了新的修改:
- 我将其中的“setValue”替换为“value”
- 我将“更新:值”替换为“输入”
其他的都一样。
然后在subform.vue中:
- 我将“:setValue.sync”替换为“v-model”
v-model 是双向绑定(bind),所以我在需要的地方使用了它。父子之间的同步(不是 child 到孙子)仍然使用同步修饰符,只是因为 parent 有很多 Prop 要传递。我可以修改它,我可以将 Prop 组合为一个对象,然后传递它。
关于javascript - 在 Parent 和 Grandchildren Vue 2 之间使用同步修饰符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49806121/