我遵循了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'
,这是有道理的,因为它尚未定义,但也不应在模块下查找,或者我是否未定义模块正确吗?
答案 0 :(得分:1)
1
const isAuthed = store.state["UserProfile"].authed; // false
2
const state:any|State = store.state
const isAuthed = state.UserProfile.authed; // false
3
const isAuthed = (<any|State>store.state).UserProfile.authed; // false
答案 1 :(得分:-1)
编辑:似乎直接访问状态是这里的问题。线
const isAuthed = store.state.UserProfile.authed;
我相信这是因为它是命名空间。解决方案是创建一个吸气剂。
const getters: GetterTree<ProfileState, RootState> = {
user(state): User {
return state.user
}
};
然后您可以像
一样访问它store.getters['UserProfile/user']
此外,请考虑使用getter访问状态数据。请参阅Getters以供参考。