Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue.js[vuex] how to dispatch from a mutation?

I have a list of filters I want to apply to a json object.

My mutations look like this:

const mutations = {     setStars(state, payload) {         state.stars = payload;         this.dispatch('filter');     },      setReviews(state, payload) {         state.reviews = payload;         this.dispatch('filter');     } }; 

Because of how filters work I need to re-apply them all again since I can't simply keep downfiltering a list because this gets me into trouble when a user de-selects a filter option.

So when a mutation is being made to a stars filter or reviews filter(user is filtering) I need to call a function that runs all my filters.

What is my easiest option here? Can I add some kind of helper function or possible set up an action which calls mutations that actually filter my results?

like image 490
Stephan-v Avatar asked Jun 01 '17 14:06

Stephan-v


People also ask

How do I dispatch action from mutation Vuex?

Mutations can't dispatch further actions, but actions can dispatch other actions. So one option is to have an action commit the mutation then trigger the filter action. Another option, if possible, would be to have all filters be getters that just naturally react to data changes like a computed property would.

Can I call action from mutation Vuex?

In Vuex, actions are functions that call mutations. Actions exist because mutations must be synchronous, whereas actions can be asynchronous. You can define actions by passing a POJO as the actions property to the Vuex store constructor as shown below. To "call" an action, you should use the Store#dispatch() function.

How do you access getters in mutations Vuex?

You can access getters in actions, because actions get context as the first argument. like this: actions: { action1: (context, payload) => { console. log(context. getters.


1 Answers

Mutations can't dispatch further actions, but actions can dispatch other actions. So one option is to have an action commit the mutation then trigger the filter action.

Another option, if possible, would be to have all filters be getters that just naturally react to data changes like a computed property would.

Example of actions calling other actions:

// store.js export default {   mutations: {     setReviews(state, payload) {       state.reviews = payload     }   }    actions: {     filter() {       // ...     }      setReviews({ dispatch, commit }, payload) {       commit('setReviews', payload)       dispatch('filter');     }   } }   // Component.vue import { mapActions } from 'vuex';  export default {   methods: {     ...mapActions(['setReviews']),     foo() {       this.setReviews(...)     }   } } 
like image 169
Matt Avatar answered Sep 20 '22 14:09

Matt