Validating Vuex State

Validating vuex states can be tricky, since in order for the state to change you have to trigger a mutation. Your first try may look like this:

<input type="text" @input="updateMessage" v-validate="'required'">
// ...
computed: {
  ...mapState({
    message: state => state.obj.message
  })
},
methods: {
  updateMessage (e) {
    this.$store.commit('updateMessage', e.target.value)
  }
}

But that doesn't work very well for input events. This is because the handlers for validator and the updateMessage method don't sync up. To fix this issue we need to enable two way binding for Vuex state which is easy to achieve using setters for computed properties and allows us to use v-model on our inputs.

So our code will look like this:

<input name="message" v-model="message" v-validate="'required|min:5'" type="text" placeholder="Your Message">
// ...
computed: {
  message: {
    get () {
      return this.$store.state.message;
    },
    set (val) {
      this.$store.commit('UPDATE_MESSAGE', val);
    }
  }
}

Demo

Edit VeeValidate Examples