我正在尝试在Vue-Typescript应用程序中创建身份验证功能。为此,我创建了一个Vuex存储模块'AuthModule'。我已经将Vuex操作映射到类组件方法。但是,当我从其他类方法调用这些操作时,会引发如下错误。
Property 'login' does not exist on type 'AuthView'.
70 | rememberMe: this.rememberMe
71 | };
> 72 | this.login(user)
| ^
73 | .then(() => this.$router.push('/home'))
74 | .catch(err => console.log(err))
75 | }
AuthModule商店
import {Action, Module, Mutation, VuexModule, getModule} from "vuex-module-decorators";
import Api from "@/helpers/Api";
import axios from "axios";
import User from "@/dao/User";
import store from '@/store'
@Module({dynamic: true, store, name: "AuthModule", namespaced: true})
class AuthModule extends VuexModule {
public token = localStorage.getItem('token') || '';
public status = '';
public user = new User();
public isLoggedIn = false;
@Mutation
public authRequest(): void {
this.status = 'loading'
}
@Mutation
public authSuccess(token: string, user: User): void {
this.token = token;
this.user = user;
this.isLoggedIn = true;
}
@Mutation
public authError() {
this.status = 'error'
}
@Action({rawError: true})
public login(user: any) {
return new Promise((resolve, reject) => {
this.context.commit('authRequest');
return Api.post('/auth/login', user)
.then(resp => {
const token = resp.data.accessToken;
const user = new User();
user.firstName = resp.data.firstName;
user.lastName = resp.data.lastName;
user.UserId = resp.data.userId;
localStorage.setItem('token', token);
Api.defaults.headers.common['Authorization'] = 'Bearer ' + token;
this.context.commit('authSuccess', {token, user});
resolve(resp)
})
.catch(err => {
this.context.commit('authError');
localStorage.removeItem('token');
reject(err)
})
})
}
}
商店index.ts
import Vue from 'vue'
import Vuex from 'vuex'
import {authModule} from "./auth/AuthModule";
Vue.use(Vuex);
export default new Vuex.Store({
modules: {
authModule
}
})
Login.ts
<script lang="ts">
import {Component, Vue} from 'vue-property-decorator'
import {mapActions} from "vuex";
@Component({
methods: {
...mapActions('authModule', ['login'])
}
})
export default class AuthView extends Vue {
private email = "";
private password = "";
private rememberMe = "";
public login(user:object) {};
performLogin() {
const user = {
email: this.email,
password: this.password,
rememberMe: this.rememberMe
};
this.login(user)
.then(() => this.$router.push('/home'))
.catch(err => console.log(err))
}
}
</script>
如果有人遇到这样的问题,请提出解决方案。
答案 0 :(得分:0)
在您的 AuthModule.store 中,您应该使用getModule
导出存储,即:
export const authModuleStore = getModule(AuthModule);
然后,您可以直接将authModuleStore
直接导入您的组件并直接引用其方法:
import { authModuleStore } from '/path/to/authModule.store';
export default class AuthView extends Vue {
private email = "";
private password = "";
private rememberMe = "";
public login(user:object) {};
performLogin() {
const user = {
email: this.email,
password: this.password,
rememberMe: this.rememberMe
};
authModuleStore .login(user)
.then(() => this.$router.push('/home'))
.catch(err => console.log(err))
}
}