DEV Community

Faizan Arif
Faizan Arif

Posted on • Updated on

How to bind Vuex with an input inside a component

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

Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode


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)


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)