How to bind input field and update vuex state at s

2019-05-27 10:17发布

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>

1条回答
We Are One
2楼-- · 2019-05-27 11:06

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

查看更多
登录 后发表回答