简体   繁体   English

如何从javascript / typescript模块文件(导入/导出)访问Vuex存储?

[英]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'但是可以从vuevuex模块导入store实例。

You can do that using Plugin. 您可以使用插件来做到这一点。

  1. When you using Plugin, you will get the store instance. 使用插件时,您将获得商店实例。
  2. Subscribe to the instance and you get the state, extract token from the state and save it to local variable. 订阅实例,您将获得状态,从状态中提取令牌并将其保存到本地变量。
  3. In the Interceptor read this module-global variable. 在拦截器中读取此模块全局变量。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM