javascript - 如何从 javascript/typescript 模块文件(导入/导出)访问 Vuex 商店?
问题描述
我有一个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 调用创建拦截器(在我的 auth 模块中)以从商店添加令牌。
Vue.http.interceptors.push((request: any) => {
// ---> store.state.token???
// request.headers.set('Authorization', 'Bearer TOKEN');
});
但是我怎样才能在不依赖我的应用程序的情况下访问商店的状态呢?
但可以从or模块import {store} from './store'
导入 store 实例。vue
vuex
解决方案
您可以使用插件来做到这一点。
- 当您使用插件时,您将获得商店实例。
- 订阅实例并获取状态,从状态中提取令牌并将其保存到局部变量。
- 在拦截器中读取这个模块全局变量。
这是我为您构建的解决方案:
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],
});
推荐阅读
- ionic2 - Ionic - 如何在离子选择上显示 [selectOptions] 中定义的自定义按钮?
- c# - 使用 LINQ 和递归从树结构(N 个嵌套列表)中获取项目 - c#
- mysql - 创建影响另一个表的触发器
- java - 如何在内部调用 API 中的某些特定抽象方法的实现?
- html - 检测div内的悬停
- java - 如何从同一个表映射多个@OneToOne 关联
- python-2.7 - 如何从 Jenkins 声明性管道运行 python 脚本?
- apache-spark - Spark 数据集 API groupByKey KeyValueGroupedDataset
- php - Laravel 查询生成器 - groupBy、map、sortBy / orderBy
- c - 推送堆栈函数收到我找不到的内存泄漏