vue.js - 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
}
}
}
}
})
当我单击“添加”按钮时,我可以看到在页面上创建了哪些字段但不在状态中(状态还没有我刚刚添加的这个字段)但是如果我刷新页面状态添加到自己这个字段。问题:这是正确的吗?还是视情况而定?我需要直接更新状态吗?
我删除了一些代码,因为当我使用大量代码时我无法询问。
解决方案
你contacts
的状态没有改变。您正在将 new 推object
送到传递给ADD_FIELD
方法的变量。
也许您可以尝试contact
在contacts
数组中查找并替换 。或者,如果它是新的,只需将其推到contacts
. 这应该在您的ADD_FIELD(...)
方法结束时发生。
推荐阅读
- react-native - 无法解压缩文件,因为 react-native 中的 zip 文件中有多个同名文件
- c# - 实体框架在两个不同的上下文中插入实体两次
- c++ - C++ 中缀到后缀转换和计算器
- datepicker - Flutter DatePicker 没有一天
- sql-server - 如何根据不同的列值更新 SQL Server 表
- r - 将 Group by 和 Slope 与 dplyr 一起使用以获取新列
- ios - 为什么我得到不同的结果取决于我在模拟器中使用的是 iPad 还是 iPhone?
- ansible - 超出重试次数时从 async_status 循环中获取有意义的错误消息
- java - 为在 Tomcat 服务器上运行的 java 网站创建 ssl 证书
- javascript - 如何在 Node.js 中获取 URL 参数的值?