[Vuejs]-Vuex and form handling using v-model

2👍

If you want to have a mutation that can update any value on your state.form object, then I’d do something like this.

In the mutation, use the key to assign the value to the right property

  mutations: {
    updateForm (state, {key, value}) {
      state.form[key] = value;
    }
  }

And in the commit, use an object as the payload that has a key and value parameters

computed: {
    name: {
      get () {
        return this.$store.state.form.name
      },
      set (value) {
        this.$store.commit('updateForm', {key:'name', value});
      }
    }
👤Daniel

1👍

    You can use mapFields to enable to way data binding
      computed: {
        ...mapFields({
          firstName: 'form.name',
          lastName: 'form.lastName',
          phoneNumber: 'form.phoneNumber',
          emailAddress: 'form.emailAddress'
        }),
      },

Add this to your mutations
import { updateField } from ‘vuex-map-fields’;

There is no need to add mutations to update the state this this done directly and using v-model you can bind these properties.

Leave a comment