DEV Community

Faizan Arif
Faizan Arif

Posted on • Edited on

2 2

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

<input
   type="text"
   :placeholder="placeholder"
   v-model="inputValue"
/>
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

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.

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay