首页 > 解决方案 > Vuex:防止输入字段更新状态/存储

问题描述

在我的 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 }}是被动的,只有在提交表单后才更新。

标签: vue.jsvuejs2vuex

解决方案


答案是使用存储中的值初始化您的初始数据。

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

不要忘记使用localUserProfileupdateProfile方法中的值更新您的商店。

您的代码也有一些错误:

  1. 您不能直接使用v-model="userProfile.name". 可能您的控制台中有错误。

推荐阅读