我可以从 Vuex 中的 getter 进行分派吗 [英] Can I do dispatch from getters in Vuex

查看:26
本文介绍了我可以从 Vuex 中的 getter 进行分派吗的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

小提琴:这里

我正在使用 Vue 2 和 Vuex 创建一个 web 应用程序.我有一个商店,我想从 getter 中获取状态数据,我想要的是如果 getter 发现数据尚未填充,它会调用 dispatch 并获取数据.

I am creating a webapp with Vue 2 with Vuex. I have a store, where I want to fetch state data from a getter, What I want is if getter finds out data is not yet populated, it calls dispatch and fetches the data.

以下是我的 Vuex 商店:

Following is my Vuex store:

const state = {
  pets: []
};

const mutations = {
  SET_PETS (state, response) {
    state.pets = response;
  }
};

const actions = {
 FETCH_PETS: (state) => {
      setTimeout(function() { 
            state.commit('SET_PETS', ['t7m12qbvb/apple_9', '6pat9znxz/1448127928_kiwi'])
    }, 1000)
 }
}

const getters = {
    pets(state){
    if(!state.pets.length){
        state.dispatch("FETCH_PETS")
    }
    return state.pets
  }
}

const store = new Vuex.Store({
  state,
  mutations,
  actions,
  getters
});

但我收到以下错误:

未捕获的类型错误:state.dispatch 不是函数(…)

Uncaught TypeError: state.dispatch is not a function(…)

我知道我可以从 Vue 组件的 beforeMount 中做到这一点,但是我有多个使用相同 Vuex 存储的组件,所以我必须在其中一个组件中执行此操作,应该使用哪个组件是以及它将如何影响其他组件.

I know I can do this, from beforeMount of Vue component, but I have multiple components which uses same Vuex store, so I have to do it in one of the components, which one should that be and how will it impact other components.

推荐答案

Getter 无法调用 dispatch,因为它们传递的是 state 而不是 store 的 context

Getters can not call dispatch as they are passed the state not context of the store

动作可以在传递上下文时调用状态、分派、提交.

Actions can call state, dispatch, commit as they are passed the context.

Getter 用于管理派生状态".

Getters are used to manage a 'derived state'.

如果您改为在需要它的组件上设置 pets 状态,那么您只需从应用的根目录调用 FETCH_PETS 并消除对 getter 的需要

If you instead set up the pets state on the components that require it then you would just call FETCH_PETS from the root of your app and remove the need for the getter

这篇关于我可以从 Vuex 中的 getter 进行分派吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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