首页 > 解决方案 > 如何从 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 实例。vuevuex

标签: javascripttypescriptvue.jsvue-componentvuex

解决方案


您可以使用插件来做到这一点。

  1. 当您使用插件时,您将获得商店实例。
  2. 订阅实例并获取状态,从状态中提取令牌并将其保存到局部变量。
  3. 在拦截器中读取这个模块全局变量。

这是我为您构建的解决方案:

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],
});

推荐阅读