typescript - 在 router.ts 中访问 Vuex store 模块的状态

标签 typescript vue.js vuex vue-router vuex-modules

我关注了this使用 TypeScript 设置带有模块的 Vuex 存储的教程。

到目前为止我有:

vuex/types.ts:

export interface RootState {
    version: string;
}

vuex/user-profile.ts:

import { ActionTree, Module, MutationTree } from 'vuex';
import { RootState } from './types';

interface User {
    firstName: string;
    uid: string;
}

interface ProfileState {
    user?: User;
    authed: boolean;
}

const state: ProfileState = {
    user: undefined,
    authed: false,
};

const namespaced: boolean = true;

export const UserProfile: Module<ProfileState, RootState> = {
    namespaced,
    state,
};

store.ts:

import Vue from 'vue';
import Vuex, { StoreOptions } from 'vuex';
import { UserProfile } from '@/vuex/user-profile';
import { RootState } from '@/vuex/types';

Vue.use(Vuex);

const store: StoreOptions<RootState> = {
  state: {
      version: '1.0.0',
  },
  modules: {
      UserProfile,
  },
};

export default new Vuex.Store<RootState>(store);

在我的 router.ts 中,我想像这样访问商店的 authed 状态:

import store from './store';
//...other imports...

const router = new Router({
//... route definitions...
});

router.beforeEach((to, from, next) => {
  const isAuthed = store.state.UserProfile.authed;
  if (to.name !== 'login' && !isAuthed) {
    next({ name: 'login' });
  } else {
    next();
  }
});

代码有效(应用程序正确重定向),但是,编译器抛出错误说 Property 'UserProfile' does not exist on type 'RootState',这是有道理的,因为它没有定义,但应该它也不在模块下查找,还是我没有正确定义模块?

最佳答案

编辑:似乎直接访问状态是这里的问题。线路

const isAuthed = store.state.UserProfile.authed;

我相信这是因为它是命名空间的。解决方案是创建一个 getter。

const getters: GetterTree<ProfileState, RootState> = {

    user(state): User {
        return state.user
    }

};

然后你就可以访问它了

store.getters['UserProfile/user']

此外,请考虑使用 getter 来访问您的状态数据。参见 Getters供引用。

关于typescript - 在 router.ts 中访问 Vuex store 模块的状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52863117/

相关文章:

reactjs - 找不到名称React $ Node React Native

javascript - 多个 v-for 用于多个对象数组 - 使用相同的索引

css - Vuetify 容器最大宽度固定

javascript - 何时使用 Vuex 从数据库初始加载状态

typescript - 使用vuex时如何在typescript语法中使用mapState函数?

javascript - 导入导出类的 typescript 发出 require(...) ,这会产生浏览器错误

typescript 语法 : { new (): T } | { new (): T }[]

node.js - 如何在 Node 中访问 Lambda 中的/tmp 文件夹?

javascript - 如何在Vue Js中选择特定的json数据并将其存储到数组中?

javascript - 如何在vuex.js中将输入中输入的文本保存在 "store"中?我哪里做错了?