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

标签 javascript typescript vue.js vue-component 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 调用创建拦截器(在我的身份验证模块内),以从商店添加 token 。

Vue.http.interceptors.push((request: any) => {
    // ---> store.state.token???
    // request.headers.set('Authorization', 'Bearer TOKEN');
  });

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

最佳答案

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

  1. 当您使用Plugin时,您将获得store实例。
  2. 订阅实例并获取状态,从状态中提取 token 并将其保存到本地变量。
  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],
});

关于javascript - 如何从 javascript/typescript 模块文件(导入/导出)访问 Vuex 存储?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52566205/

相关文章:

javascript - 将多个参数控制为一个函数的最佳代码结构

javascript - 使用 event.target.id 从 bind(this) 获取 id 时意外使用 'event' no-restricted-globals

javascript - 如何仅通过 Javascript 访问我的 GrapheneDB neo4j 数据库

javascript - 从外部类调用 Vue 组件内部的方法

javascript - 如何添加多个属性 - vue.js

javascript - "Tank Wars"游戏中随机土地的算法

javascript - 表格行折叠?

reactjs - 如何在 TypeScript 中 'specialize' React 组件?

javascript - typescript 错误运行时错误: Cannot read property 'prototype' of undefined when extending

javascript - 创建一个使用 Vue 和 Typescript 的 Meteor 项目