【发布时间】:2020-09-16 06:58:14
【问题描述】:
<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
}
}
}
}
})
当我单击“添加”按钮时,我可以看到在页面上创建了哪些字段但未处于状态(状态还没有我刚刚添加的此字段)但是如果我刷新页面状态添加到自己这个字段。
问题:这是正确的吗?还是视情况而定?我需要直接更新状态吗?
我删除了一些代码,因为当我使用大量代码时我无法询问。
【问题讨论】:
-
您的
state配置看起来不正确(contacts是什么?)并且您从未在您的突变中更改state上的任何内容 -
你的
getContactgetter 在哪里? -
我更改了引用该州的联系人
-
const contacts = ...并没有真正告诉我任何事情。请提供一些细节 -
``` [ { id: 'ssfg', fields: [ { fieldName: 'ФИО', fieldValue: 'Иванов Иван' }, { fieldName: 'Номер телефона', fieldValue: '+79523695475 ' } ] } ] ``` 我使用插件来保存对状态的更改,但您可以在上面看到默认状态