我按照本教程使用 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,
};
商店.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'
,这是有道理的,因为它没有定义,但它不应该在模块下查看,还是我没有正确定义模块?