Form handling restrictions when using Vuex
Using Vue's v-model
featurewith the Vuex state results in a direct modification of the state, which is forbidden.
Take a look at the following example:
<input v-model="$store.state.message">
In this example, $store.state
is mutated directly by v-model
, and if strict mode is enabled, it will result in an error being thrown.
There is more than one way to solve this problem, and I will show you the one that, in my opinion, is better: You can use a mutable computed property that accesses the state
property when read and commits a mutation when set:
<input v-model="message"> // ... computed: { message: { get () { return this.$store.state.obj.message; }, set (value) { this.$store.commit('updateMessage', value); } } }
Using a mutable computed property also allows you to add some validation before committing the corresponding mutation.
The following is a possible code for the mutation that gets committed:
// ... mutations...