[英]How to access Vuex store from javascript/typescript modules files (import/export)?
I have a vue
application. 我有一个
vue
申请。
How to access the store from javascript/typescript modules files (import/export)? 如何从javascript / typescript模块文件(导入/导出)访问商店?
for example, I create auth-module that export state, actions, mutations. 例如,我创建了用于导出状态,操作,突变的身份验证模块。
export const auth = {
namespaced: true,
state,
actions,
mutations,
getters,
};
In my app I import the module to my store: 在我的应用程序中,我将该模块导入到我的商店:
Vue.use(Vuex);
export const store = new Vuex.Store({
modules: {
auth,
}
});
Now, I want to create interceptor (inside my auth-module) for my http calls to add the token from the store. 现在,我想为我的http调用创建拦截器(在我的auth-module内部)以从存储中添加令牌。
Vue.http.interceptors.push((request: any) => {
// ---> store.state.token???
// request.headers.set('Authorization', 'Bearer TOKEN');
});
But how can I get access to the state of the store without be depend on my app? 但是,如何不依赖于我的应用程序就可以访问商店的状态?
import {store} from './store'
but it's okay to import the store instance from vue
or vuex
module. import {store} from './store'
但是可以从vue
或vuex
模块导入store实例。
You can do that using Plugin. 您可以使用插件来做到这一点。
Here is the solution I built for you: 这是我为您打造的解决方案:
StoreTokenInterceptorPlugin.ts 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;
});
};
in your app store: 在您的应用商店中:
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],
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.