I have a search form and an object like this:
<!-- Search.vue -->
<template>
<form>
<input type="text" v-model="form.firstName">
<input type="text" v-model="form.lastName">
</form>
</template>
<script>
export default {
data() {
return {
form: {
firstName: '',
lastName: '',
}
}
}
</script>
I'm wanting to move the form data object to my Vuex store so I can save the form settings if the user navigates away from this component.
Ideally, I would like to do something like this, but even though this works, I get errors:
<template>
<form>
<input type="text" v-model="form.firstName">
<input type="text" v-model="form.lastName">
</form>
</template>
<script>
export default {
computed: {
form() {
get() {
return this.$store.state.form;
},
set(values) {
this.$store.commit('SET_FORM', values)
}
},
}
}
</script>
// store.js
export default {
state: {
form: {
firstName: '',
lastName: '',
}
},
mutations: {
SET_FORM(state, values) {
state.form = values;
},
},
}
Error: [vuex] do not mutate vuex store state outside mutation handlers.
Here's my alternative approach, but I feel like this is way too complicated.
<template>
<form>
<input type="text" v-model="firstName">
<input type="text" v-model="lastName">
</form>
</template>
<script>
export default {
computed: {
firstName() {
get() {
return this.$store.state.form.firstName;
},
set(value) {
this.$store.commit('SET_FORM', { attribute: 'firstName', value: value })
}
},
lastName() {
get() {
return this.$store.state.form.lastName;
},
set(value) {
this.$store.commit('SET_FORM', { attribute: 'lastName', value: value })
}
},
}
}
</script>
// store.js
export default {
state: {
form: {
firstName: '',
lastName: '',
}
},
mutations: {
SET_FORM(state, { attribute, value }) {
state.form[attribute] = value;
},
},
}
Anyone know why I would be getting the Vuex errors and how I could fix them? Either that or know of a better way to approach this?
Thanks!