Reputation: 3082
vuex do not mutate vuex store state outside mutation handlers
I tried to look for something here, because the error is very common, but I couldn't solve it yet
I'm trying to create a stateful form with vuex
Component
<el-form ref="form" :model="form" label-width="130px">
<el-form-item label="Entrada">
<el-input v-model="form.dataEntrada"></el-input>
</el-form-item>
</el-form>
Computed
computed: {
form: {
get () {
return this.$store.state.form
},
set (value) {
this.$store.commit('setForm', value)
}
}
}
Store
state: {
form: {
dataEntrada: ''
},
},
mutations: {
setForm(state, payload){
state.form = payload
}
}
actions: {},
getters: {},
Upvotes: 3
Views: 516
Reputation: 1849
You are trying to map v-model
to a piece of Vuex state
. Instead use @input
or @change
in the input to commit the changes to the store and use :value
to bind the value from the store.
<el-input :value="form.dataEntrada" @input="updateValue" />
and in the script
computed: { form: function() { return this.$store.state.form }},
methods: { updateValue: function(e) { this.$store.commit('setValue', e.target.value) }}
Template
<template>
<div class="hello">
<el-form ref="form" :model="form" label-width="130px">
<el-row>
<el-col :span="4">
<el-form-item label="Entrada">
<el-input v-model="form.dataEntrada"></el-input>
</el-form-item>
</el-col>
<el-col :span="4">
<el-form-item label="Fornecedor">
<el-input v-model="form.fornecedor"></el-input>
</el-form-item>
</el-col>
<el-col :span="4">
<el-form-item label="Codigo">
<el-input v-model="form.nfe.codigo"></el-input>
</el-form-item>
</el-col>
<el-col :span="4">
<el-form-item label="Numero">
<el-input v-model="form.nfe.numero"></el-input>
</el-form-item>
</el-col>
</el-row>
<el-form-item>
<el-button type="primary" @click="onSubmit">Criar</el-button>
</el-form-item>
</el-form>
</div>
</template>
Vue
data() {
return {
form: this.$store.state.form
}
},
methods: {
onSubmit() {
this.$store.commit("setForm", this.form);
}
}
store
In case if you are not setting the form elements to required and want to update only the changed fields, below is the code.
mutations: {
setForm(state, payload) {
state.form = {
...state.form,
...payload
};
}
},
Upvotes: 3