Sometimes you need to bind input fields with a vuex state. You can easily achieve that, all you need is an input bind to a computed property. Lemme explain it by giving you an example!
Let's say we've an input having a v-model on it as follows
<input
type="text"
:placeholder="placeholder"
v-model="inputValue"
/>
Most of the time, inputs are bind to a data property in vuejs. To bind an input to vuex, you need to add computed
property as follows
computed: {
inputValue: {
get () {
// you can right any getter/state here
return this.$store.stateName
},
set (val) {
// you can right any getter/state here
this.$store.commit(βmutationNameβ, val)
}
}
}
Explanation
What we're doing in this computed property
is, whenever the value of our input is changing, we're mutating our store with fresh value and inside get
method of our computed property, we're always returning the state of our store (it'll be fresh value always)
Conclusion
To bind a vuex store and an input, you need to have an input with a v-model
on it and you need to write a computed property which mutates store each time the value is changed and returns the latest state of the store. It can be state/getter of that store.
Top comments (0)