【问题标题】:How to access Vuex store from javascript/typescript modules files (import/export)?如何从 javascript/typescript 模块文件(导入/导出)访问 Vuex 商店?
【发布时间】:2019-03-05 02:14:13
【问题描述】:

我有一个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');
  });

但是我怎样才能在不依赖我的应用的情况下访问商店的状态呢? import {store} from './store' 但可以从 vuevuex 模块导入 store 实例。

【问题讨论】:

    标签: javascript typescript vue.js vue-component vuex


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2021-01-23
      • 2022-09-23
      • 2018-05-19
      • 2019-04-07
      • 2012-11-06
      • 2020-02-05
      • 2023-03-11
      • 2015-05-08
      相关资源
      最近更新 更多