如何从vuex中的不同存储模块访问存储状态



EDIT:我找到了一个解决方案,它只是在我的vue模块中的mounted((函数中作为参数传递令牌:

mounted(){
this.$store.dispatch("fetchData", this.$store.state.auth.user.token)

在商店里,我使用我的异步函数如下:

async fetchData({commit}, id)

我想从我的存储中进行API调用,但我也有存储在同一位置的API调用所需的用户信息(userId,jwttoken(。

这是我的商店:

import Vue from "vue";
import Vuex from "vuex";
import createPersistedState from "vuex-persistedstate";
import auth from "./modules/auth";
import prod from "./modules/prod";
Vue.use(Vuex);
export default new Vuex.Store({
modules: {
auth,
prod
},
plugins: [createPersistedState()],
});

这是我在商店里的身份验证模块:

import axios from "axios";
const state = {
user: null,
};
const getters = {
isAuthenticated: (state) => !!state.user,
StateUser: (state) => state.user,
};
const actions = {
async Register({ dispatch }, form) {
await axios.post("user/signup", form);
await dispatch("LogIn", form);
},
async LogIn({ commit }, User) {
const response = await axios.post("user/login", User);
console.log(response)
await commit("setUser", response.data);
},
async LogOut({ commit }) {
let user = null;
commit("logout", user);
},
};
const mutations = {
setUser(state, user) {
state.user = user;
},
logout(state) {
state.user = null;
},
};
export default {
state,
getters,
actions,
mutations,
};

这就是我想在另一个存储文件中调用它的地方,行为this$store.state.auth.user.token获取API调用所需的令牌:

//store/modules/prod.js
import axios from "axios";
const state = {
products: null,
};
const actions = {
async fetchData({commit}) {
const headers = {
authorization: "Bearer " + this.$store.state.auth.user.token,
};
let resp = await axios.get("product", {
headers
});
await commit("SET_PRODUCTS", resp.data)
}
};
const mutations = {
SET_PRODUCTS(state, products) {
state.products = products
}
};
export default {
state,
actions,
mutations,
};

我称之为这样的组件:

products(){
return this.$store.state.products
}
},
mounted(){
this.$store.dispatch("fetchData")

但是,来自存储的请求从未发送到API,因为它无法读取令牌。我得到了";无法读取未定义的(读取状态(

我也试过这样导入它,但它说令牌是未定义的:

import auth from "../modules/auth"
const headers = {
authorization: "Bearer " + auth.user.token,
};

我在网上读到,你应该通过Getters从非vue模块访问商店,但我也没能让它正常工作,这是正确的方法吗?

Actions以上下文对象为参数,您可以使用它来访问rootState。查看文档以了解其他可用选项。https://vuex.vuejs.org/api/#actions

const actions = {
async fetchData({commit, rootState}) {
const headers = {
authorization: "Bearer " + rootState.auth.user.token,
};
let resp = await axios.get("product", {
headers
});
await commit("SET_PRODUCTS", resp.data)
}
};

最新更新