Vue.js[vuex] 如何从突变中调度? [英] Vue.js[vuex] how to dispatch from a mutation?

查看:23
本文介绍了Vue.js[vuex] 如何从突变中调度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个要应用于 json 对象的过滤器列表.

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?

推荐答案

Mutations 不能调度进一步的动作,但动作可以调度其他动作.所以一种选择是让一个动作提交突变,然后触发过滤器动作.

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.

如果可能的话,另一种选择是让所有过滤器都是 getter,它们像计算属性一样自然地对数据变化做出反应.

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(...)
    }
  }
}

这篇关于Vue.js[vuex] 如何从突变中调度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆