我关注了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/