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

≯℡__Kan透↙ 提交于 2019-11-30 17:23:45

问题


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:


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



来源:https://stackoverflow.com/questions/44456528/how-to-bind-input-field-and-update-vuex-state-at-same-time

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!