I would like to assign setter methods via mapState
. I currently use a workaround where I name the variable that I am interested in (todo
) as a temporary name (storetodo
) and then refer to it in another computed variable todo
.
methods: { ...mapMutations([ 'clearTodo', 'updateTodo' ]) }, computed: { ...mapState({ storetodo: state => state.todos.todo }), todo: { get () { return this.storetodo}, set (value) { this.updateTodo(value) } } }
I would like to skip the extra step and define the getter, setter directly within mapState
.
Why would I want to do this?
The normal approach would be use mapMutations
/mapActions
& mapState
/mapGetters
without the computed get/set combination that I have illustrated above and to reference the mutation directly in the HTML:
<input v-model='todo' v-on:keyup.stop='updateTodo($event.target.value)' />
The getter/setter version allows me to simply write:
<input v-model='todo' />
Mapping getters is similar to mapping state. Getters provide a way of getting a derived computed state from the store e.g a function that returns products based on popularity. Vuex also provides a mapGetters helper function to map getters to local computed properties.
The Map state ( "Type": "Map" ) can be used to run a set of steps for each element of an input array. While the Parallel state executes multiple branches of steps using the same input, a Map state will execute the same steps for multiple entries of an array in the state input.
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.
You can't use a getter/setter format in the mapState
what you can try is directly return the state in your get()
and remove mapState
from the computed property
computed: { todo: { get () { return this.$store.state.todos.todo}, set (value) { this.updateTodo(value) } } }
Here is a related but not same JsFiddle example
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