Sau*_*abh 14 javascript vue.js vue-component vuex vuejs2
小提琴:这里
我正在使用Vuex和Vuex创建一个webapp.我有一个商店,我想从getter获取状态数据,我想要的是如果getter发现数据尚未填充,它会调用dispatch并获取数据.
以下是我的Vuex商店:
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
});
Run Code Online (Sandbox Code Playgroud)
但我收到以下错误:
未捕获的TypeError:state.dispatch不是函数(...)
我知道我可以从beforeMountVue组件中做到这一点,但是我有多个组件使用相同的Vuex存储,所以我必须在其中一个组件中执行它,应该是哪个组件以及它将如何影响其他组件.
因为它们是通过吸气剂不能打电话调度state没有context实体店
动作可以在传递上下文时调用state,dispatch,commit.
吸气剂用于管理"派生状态".
如果您改为pets在需要它的组件上设置状态,那么您只需FETCH_PETS从应用程序的根目录调用并删除对getter的需求
小智 8
我知道这是一篇较旧的帖子,我不确定这是否是好的做法,但我执行了以下操作以从我的商店模块中的 getter 发送:
import store from "../index"
并像这样使用我的吸气剂中的商店:
store.dispatch("moduleName/actionName")
我这样做是为了确保数据不存在时可用。
有同样的问题..还希望所有 Vue-Instances 自动加载一些东西,并写了一个 mixin:
store.registerModule('session', {
namespaced: true,
state: {
session: {hasPermission:{}},
sessionLoaded:false
},
mutations: {
changeSession: function (state, value)
{
state.session = value;
},
changeSessionLoaded: function (state)
{
state.sessionLoaded = true;
}
},
actions: {
loadSession(context)
{
// your Ajax-request, that will set context.state.session=something
}
}
});
Vue.mixin({
computed: {
$session: function () { return this.$store.state.session.session; },
},
mounted:function()
{
if(this.$parent==undefined && !this.$store.state.session.sessionLoaded)
{
this.$store.dispatch("session/loadSession");
this.$store.commit("changeSessionLoaded");
}
},
});
Run Code Online (Sandbox Code Playgroud)
因为它每个 vue-instance 和 store 只加载一个并且它会自动包含在每个 vue-instance 中,所以不需要在每个主应用程序中定义它