Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>

like image 377
Sylar Avatar asked Jun 09 '17 11:06

Sylar


People also ask

How do I update my Vuex state?

Vuex stores are reactive. When Vue components retrieve state from it, they will reactively and efficiently update if the store's state changes. You cannot directly mutate the store's state. The only way to change a store's state is by explicitly committing mutations.

What is the use of mapState in Vuex?

Mapping State Vuex provides a helper function called mapState to solve this problem. It is used for mapping state properties in the store to computed properties in our components. The mapState helper function returns an object which contains the state in the store.

Does Vuex keep state on refresh?

However, when the page is refreshed, the data in vuex will be reinitialized, resulting in data loss. Because the data in vuex is saved in the running memory, when the page is refreshed, the page will reload the vue instance, and the data in vuex will be re assigned.

What is difference between mutation and action in Vuex?

Mutations are intended to receive input only via their payload and to not produce side effects elsewhere. While actions get a full context to work with, mutations only have the state and the payload .


1 Answers

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

like image 74
Vamsi Krishna Avatar answered Oct 19 '22 22:10

Vamsi Krishna