在我的Vuex应用程序中,我有一个update
表单,该表单用用户凭据(来自Vuex存储)预填充了输入字段,然后在提交时将表单提交到数据源。
因此,我需要在页面上显示用户详细信息,但是当用户更改表单中的值时,我不希望它们被(反应式地)更新,因为在我的情况下,如果用户不这样做,那将产生误导完成表格后离开页面并返回页面。然后看起来数据已更新(尚未提交表单,但尚未更新)。
以下是我的代码段:
表格(HTML):
<input
v-model.trim="userProfile.name"
:value="userProfile.name"
type="text" >
</input>
<input
v-model.trim="userProfile.position"
:value="userProfile.position"
type="text" >
</input>
<div>
{{ userProfile.name }} {{ userProfile.position }}
</div>
Vue代码:
computed: {
...mapState(["userProfile"]),
},
methods: {
updateProfile() {
this.$store.dispatch("updateProfile", {
name: this.name !== "" ? this.name : this.userProfile.name,
position: this.position !== "" ? this.position : this.userProfile.position,
})
}
},
仅是为了澄清这段代码,我的问题是我不希望{{ userProfile.name }}
{{ userProfile.position }}
是被动的,并且仅在提交表单后才进行更新。
答案 0 :(得分:1)
答案是使用商店中的值初始化您的初始数据。
export default {
...
data() {
const localUserProfile = JSON.parse(JSON.stringify(this.store.state.userProfile))
return {
localUserProfile
}
},
...
}
<input
v-model.trim="localUserProfile.name"
type="text" >
</input>
<input
v-model.trim="localUserProfile.position"
type="text" >
</input>
<div>
{{ userProfile.name }} {{ userProfile.position }}
</div>
通知:您应创建store.state.userProfile
的独立副本,以使用JSON.parse(JSON.stringify(this.store.state.userProfile))
或lodash.clonedeep
。
别忘了用localUserProfile
方法中的updateProfile
中的值更新商店。
您的代码也有一些错误:
v-model="userProfile.name"
更改商店的状态。控制台中可能有错误。