[Vuejs]-Vuex : state change not updating input field

4👍

Note: I tested this locally but I don’t know exactly how the store state looks from the question.

The <input> can be two-way bound with v-model, instead of computed or watched. It can be initialized with a value from the store (I used the mounted lifecycle hook below). The store state is updated only on button click.

<input v-model="firstName"/>
<button @click="updateName">Update</button>
import { mapActions, mapGetters } from 'vuex'

export default {
  data () {
    return {
      firstName: ''
    }
  },
  
  computed: mapGetters(['getFirstName']),

  methods: {
    ...mapActions(['UPDATE_FIRST_NAME']), // get the action from the store

    updateName () {
      // validations can go here etc
      this.UPDATE_FIRST_NAME(this.firstName) // update vuex store state
    }
  },

  mounted () {
    this.firstName = this.getFirstName // initialize this.firstName -> <input> 
  }
}

With this solution, you’d have to make sure to create the getter in your store, as in the following example:

const state = {
  user: {
    firstName: ''
  }
}

const getters = {
  getFirstName: state => state.user.firstName
}

1👍

You need to watch the state variables. When it change the value, the the watch function will fire.

 export default {
    data() {
        return {
            dummy_name: '',
            first_name: '',
        }
    },
    created(){
    },
    computed: {
        dummy_name() {
            return this.$store.state.user.first_name
        },
    watch: {
       dummy_name() {
            this.first_name = this.dummy_name
       }
    }

Hope this will help, and get some idea how watch and computed work.

1👍

This is an old question, but I ran into the same problem yesterday and the solution was to use the .prop modifier on the input value attribute like so:

<input :value.prop="first_name" @change="updateName" />

A quote from quite random place in the docs says:

For some properties such as value to work as you would expect, you will need to bind them using the .prop modifier.

Hope this helps someone!

Leave a comment