我有一个 vue
应用程序。
如何从 javascript/typescript 模块文件(导入/导出)访问商店?
例如,我创建了导出状态、操作、突变的 auth-module。
export const auth = {
namespaced: true,
state,
actions,
mutations,
getters,
};
在我的应用程序中,我将模块导入到我的商店:
Vue.use(Vuex);
export const store = new Vuex.Store({
modules: {
auth,
}
});
现在,我想为我的 http 调用创建拦截器(在我的身份验证模块内),以从商店添加 token 。
Vue.http.interceptors.push((request: any) => {
// ---> store.state.token???
// request.headers.set('Authorization', 'Bearer TOKEN');
});
但是我怎样才能在不依赖我的应用程序的情况下访问商店的状态呢?
从 './store' 导入 {store}
但可以从 vue
或 vuex
模块导入 store 实例。
最佳答案
您可以使用插件来做到这一点。
- 当您使用Plugin时,您将获得store实例。
- 订阅实例并获取状态,从状态中提取 token 并将其保存到本地变量。
- 在拦截器中读取此模块全局变量。
这是我为您构建的解决方案:
StoreTokenInterceptorPlugin.ts
import Vue from 'vue';
import VueResource from 'vue-resource';
import { get } from 'lodash';
Vue.use(VueResource);
export const StoreTokenInterceptorPlugin = (store: any) => {
let token: string | null = null;
(Vue.http.interceptors as any).push((request: any) => {
if (token && !request.headers.get('Authorization')) {
request.headers.set('Authorization', `Bearer ${token}`);
}
});
store.subscribe((mutation: any, state: any) => {
token = get(state, 'auth.token') || null;
});
};
在您的应用商店中:
import Vue from 'vue';
import Vuex from 'vuex';
import { auth, StoreTokenInterceptorPlugin } from '@modules/auth';
Vue.use(Vuex);
export const store = new Vuex.Store({
state,
modules: {
auth,
} as any,
....
plugins: [StoreTokenInterceptorPlugin],
});
关于javascript - 如何从 javascript/typescript 模块文件(导入/导出)访问 Vuex 存储?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52566205/