我有以下情况:
组件Textfield:
<v-text-field
v-model="form.profile.mobile_business"
label="Mobile"
prepend-inner-icon="mdi-cellphone"
></v-text-field>我通过以下方式获得当前值:
data() {
return {
form: {
profile: JSON.parse(JSON.stringify(this.$store.getters["user/Profile"])),
},
};
},我有一个提交按钮,它调用此方法:
updateUserProfile() {
this.$store.dispatch("user/updateProfile", this.form.profile);
}一切都很完美。在我的商店调度中,我调用API并通过我的突变更新商店:
context.commit('UPDATE_PROFILE', profile);在这一步之前没有错误。
但是,如果我再次更改表单输入-在我按下submit按钮后,我得到:
vuex:不要变异vuex存储状态外部突变。
但是,我不想在更改表单输入的值时更改vuex存储。只有当有人按下提交按钮时,才应该更新它。
发布于 2019-11-12 19:58:51
v-model提供双向数据绑定.更改视图中的任何内容都将自动尝试直接更新模型,而不是通过突变。谢天谢地,Vue允许计算属性上的get和set帮助我们克服这一问题。
应该在textfield组件上使用get和set方法添加计算属性。看起来会是这样的:
computed: {
userProfile: {
get() {
JSON.parse(JSON.stringify(this.$store.getters["user/Profile"]));
},
set() {
// only commit the changes to the form, do not submit the action that calls the API here.
this.$store.commit("user/updateProfile", this.form.profile)
}
}然后,您的v-model属性应该设置为这个新创建的属性,任何“set”操作(读:用户更改输入值)都将调用该操作,而不是直接在Store中设置值。
下面是一个活生生的例子:CodePen
发布于 2019-11-13 14:21:28
我就这样解决了:
form: {
profile: _.cloneDeep(this.$store.getters['user/Profile'])
},并添加了一个手表处理程序:
form: {
handler: _.debounce(function (form) {
console.log("watch fired");
}, 500), deep: true
}因此,如果用户更改了值,什么也不会发生(除了我的console.log操作)。如果他按下提交按钮,商店调度操作将被触发。
https://stackoverflow.com/questions/58825104
复制相似问题