Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mapState with setter

Tags:

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' /> 
like image 401
Chris Avatar asked May 30 '17 21:05

Chris


People also ask

What are mapGetters?

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.

What is mapState?

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.

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.


1 Answers

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

like image 189
Vamsi Krishna Avatar answered Oct 11 '22 03:10

Vamsi Krishna