Search code examples
vue.jsvuejs2vuex

How to bind input field and update vuex state at same time


Im coming from a React background and it's simply enough to set your state from a prop and you could call setState({...}) to update the state, so, with vue / vuex, I find it difficult.

To simplify:

Vuex State

name: "Foo bar"

Vuex Action

addName

I can change the state no problem but I need to bind an input field and when change, the state is updated. Think of this as an update form where the user details are already pre-filled and they can change their name.

<input @change="addName(newName) v-model="newName" />

I could add a watch to watch for newName and update the state but, I need to pre-fill the input with the state. Ha! I could use beforeMount() but my state is not loaded as yet.

computed: {
  ...mapState([
  'name'
  ]),
},
beforeMount() {
  // this.newName = this.name
  console.log('Mounted') // Shows in console
  console.log(this.name) // nothing
}

Name shows in templete <pre>{{ name }}</pre>


Solution

  • Yo can use a computed setter

    computed:{
        name:{
            get: function(){ 
                return store.state.name; 
            }, 
            set: function(newName){ 
                store.dispatch('addName',newName); 
            }
        }
    } 
    enter code here
    

    And set the v-model to the computed property name in your <input> tag :

    <input v-model="name" />

    Here is the working jsfiddle