And*_*e12 8 typescript vue.js vue-router vuex vuex-modules
我按照本教程使用TypeScript设置了包含模块的Vuex存储.
到目前为止,我有:
vuex/types.ts:
export interface RootState {
version: string;
}
Run Code Online (Sandbox Code Playgroud)
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,
};
Run Code Online (Sandbox Code Playgroud)
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);
Run Code Online (Sandbox Code Playgroud)
在我的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();
}
});
Run Code Online (Sandbox Code Playgroud)
代码工作(应用程序重定向正确),但是,编译器抛出错误说Property 'UserProfile' does not exist on type 'RootState',这是有道理的,因为它没有定义,但是它不应该在模块下看,或者我没有正确定义模块?
Dan*_*jel -1
编辑:似乎直接访问状态是这里的问题。线
const isAuthed = store.state.UserProfile.authed;
Run Code Online (Sandbox Code Playgroud)
我相信发生这种情况是因为它是命名空间的。解决方案是创建一个 getter。
const getters: GetterTree<ProfileState, RootState> = {
user(state): User {
return state.user
}
};
Run Code Online (Sandbox Code Playgroud)
然后你可以像这样访问它
store.getters['UserProfile/user']
Run Code Online (Sandbox Code Playgroud)
另外,请考虑使用 getter 来访问您的状态数据。请参阅吸气剂以供参考。
| 归档时间: |
|
| 查看次数: |
1265 次 |
| 最近记录: |