首页 > 解决方案 > Vuex 状态不重新加载就不会更新

问题描述

  <template>
    <ContactField
      v-for="(field, $fieldIndex) in contact.fields"
      :key="$fieldIndex"
      :fieldIndex="$fieldIndex"
      :contact="contact"
      :fieldName="field.fieldName"
      v-model="field.fieldValue"
    />
    <div>
      Add field
      <input type="text" v-model="newFieldName" />
      <input type="text" v-model="newFieldValue" />
      <button @click="addFieldToContact">Add</button>
    </div>
    <div>
      <button @click="saveChanges">Save</button>
    </div>
  </div>
</template>
export default {
  data() {
    return {
      newFieldName: '',
      newFieldValue: '',
    }
  },
  components: {
    ContactField
  },
  computed: {
    id() {
      return this.$route.params.id
    },
    ...mapGetters(['getContact']),
    contact() {
      return this.getContact(this.id)
    }
  },
  methods: {
    addFieldToContact() {
      this.$store.commit('ADD_FIELD', {
        contact: this.contact,
        fieldName: this.newFieldName,
        fieldValue: this.newFieldValue
      })
      this.newFieldName = ''
      this.newFieldValue = ''
    }
  }
}

Vuex商店

const contacts = ...
export default new Vuex.Store({
  state: {
    contacts
  },
  mutations: {
    ADD_FIELD(state, { contact, fieldName, fieldValue }) {
      contact.fields.push({
        fieldName: fieldName,
        fieldValue: fieldValue
      })
    }
  },
getters: {
    getContact: state => id => {
      for (const contact of state.contacts) {
        if (contact.id == id) {
          return contact
        }
      }
    }
  }
})

当我单击“添加”按钮时,我可以看到在页面上创建了哪些字段但不在状态中(状态还没有我刚刚添加的这个字段)但是如果我刷新页面状态添加到自己这个字段。问题:这是正确的吗?还是视情况而定?我需要直接更新状态吗?
我删除了一些代码,因为当我使用大量代码时我无法询问。

标签: vue.jsvuejs2vuex

解决方案


contacts的状态没有改变。您正在将 new 推object送到传递给ADD_FIELD方法的变量。

也许您可以尝试contactcontacts数组中查找并替换 。或者,如果它是新的,只需将其推到contacts. 这应该在您的ADD_FIELD(...)方法结束时发生。


推荐阅读