Vue中input绑定对象属性实现单向绑定不生效问题
问题根因
- 你的
inputData是计算属性返回的内容,每次计算都会执行cloneDeep生成全新对象,就算你修改了input对应的值,下一次计算属性触发重新计算时,会重新从Vuex getter拉取原始数据做深拷贝,之前的修改会直接被覆盖,自然无法同步到视图。 - 你使用的是
:value单向绑定,没有配套输入事件将修改后的值同步回数据源,修改input的内容后不会更新原始状态,自然不会触发视图刷新。 cloneDeep生成的对象已经脱离了Vuex原有的响应式关联,直接修改拷贝对象不会触发Vue的响应式更新逻辑。
解决方案
方案1:遵循Vuex单向数据流同步更新
如果你的修改需要实时同步到Vuex状态,按如下方式调整:
- 移除计算属性中的
cloneDeep,直接返回Vuex getter的原始响应式数据
const inputData = computed(() => store.getters['expense/getInitForm'])
- 给input绑定
v-model,同时通过带setter的计算属性触发Vuex mutation更新状态:
// 定义可写计算属性同步Vuex const formField = (index, attribute) => computed({ get() { return store.getters['expense/getInitForm'][index][attribute].value }, set(newVal) { // 调用你提前定义好的Vuex mutation更新对应字段 store.commit('expense/updateFormField', { index, attribute, value: newVal }) } })
<input type="number" v-model="formField(index, attribute)" :name="`expense_voucher[line_items_attributes][${index}][${inputData[index][attribute].attribute}]`" >
方案2:本地缓存临时修改提交时同步
如果你的业务场景需要先做临时修改,全部确认后再统一提交到Vuex,就不要把深拷贝逻辑放在计算属性中,改为组件初始化时深拷贝一次存入本地响应式变量:
// 组件初始化时深拷贝一次做本地缓存 const localInputData = ref(cloneDeep(store.getters['expense/getInitForm'])) // 提交表单时再统一同步到Vuex const submit = () => { store.commit('expense/updateWholeForm', localInputData.value) }
input直接绑定本地响应式变量即可:
<input type="number" v-model="localInputData[index][attribute].value" :name="`expense_voucher[line_items_attributes][${index}][${localInputData[index][attribute].attribute}]`" >
内容的提问来源于stack exchange,提问作者user16732355
相关产品推荐
相关产品推荐

