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>
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.
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.
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.
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 .
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With