Reputation: 1
<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 store
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
}
}
}
}
})
When i click button "add" i can see what fields created on page but not in state(state hasn't this field's that i add just now) but if i refresh page state add to yourself this fields.
Question: is this correct? Or it depends on the situation? Do I need to update state directly?
Some code i delete because i cant ask when i use a lot of code.
Upvotes: 0
Views: 270
Reputation: 518
Your contacts
are not changed trough the state. You are pushing your new object
to the variable passed to the ADD_FIELD
method.
Maybe you can try to find and replace the contact
in your contacts
array. Or if it is new one just push it to contacts
. This should happen at the end of your ADD_FIELD(...)
method.
Upvotes: 1