实现登录模块
知识点
- axios如何在typescript中使用
- 组件的基本使用
- prop实践
- 路由跳转
- vuex的基本使用
- methods基本使用
目录介绍
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/ff64680a5d45f2a602fa033d629cfa5a.png)
登录界面
<!--
* @Description:
* @Version: 1.0
* @Autor: solid
* @Date: 2022-03-25 11:15:35
* @LastEditors: solid
* @LastEditTime: 2022-04-04 16:04:32
-->
<template>
<div class="login">
<el-card style="width: 550px">
<Header :title="title"></Header>
<el-form
status-icon
ref="ruleForm"
label-width="100px"
class="ruleForm"
>
<el-form-item label="管理用户名" prop="username">
<el-input v-model="user.username"></el-input>
</el-form-item>
<el-form-item label="管理密码" prop="password">
<el-input
type="password"
v-model="user.password"
autocomplete="off"
@keyup.enter.native="HandlerLogin"
></el-input>
</el-form-item>
<el-form-item>
<el-button
type="primary"
:loading="isLoading"
@click="HandlerLogin"
>登录</el-button
>
</el-form-item>
</el-form>
</el-card>
</div>
</template>
<script lang="ts">
import {Component,Vue} from "vue-property-decorator"
import Header from '@/components/Header.vue'
import {UserModule} from '@/store/modules/user'
@Component({
name:"login",
components:{
Header
}
})
export default class Login extends Vue{
private user={
username:"",
password:"",
}
private title="登录界面"
private isLoading=false
private async HandlerLogin(){
if(this.user.username=="" ||this.user.password==""){
this.$message.warning("用户名或密码不能为空")
return
}
await UserModule.Login(this.user)
}
}
</script>
<style scoped>
.login {
height: 100%;
text-align: center;
display: flex;
justify-content: center;
align-items: center;
}
.issuer {
font-size: 26px;
font-weight: bold;
margin-bottom: 50px;
}
</style>
request.ts
import axios from 'axios'
import { Message } from "element-ui";
const baseURL = process.env.VUE_APP_BASE_API
? process.env.VUE_APP_BASE_API
: "";
const service = axios.create({
baseURL,
timeout: 30000
})
service.interceptors.request.use(
(config) => {
return config
},
(error) => {
console.log(error)
return Promise.reject(error)
}
)
service.interceptors.response.use(
response => {
const res = response.data;
if (res.code !== 0) {
Message({
message: res.message || "Error",
type: "error",
duration: 5 * 1000
});
return Promise.reject(new Error(res.message || "Error"));
} else {
return response;
}
},
error => {
Message({
message: error.message,
type: "error",
duration: 5 * 1000
});
return Promise.reject(error);
}
);
export function getData(url: string, params: object) {
return service({
url,
method: 'get',
params
})
.then(res => res.data)
.catch(error => error.response)
}
export function postData(url: string, data: object) {
return service({
url,
method: 'post',
data
})
.then(res => res.data)
.catch(error => error.response)
}
store/index.ts
import Vue from "vue";
import Vuex from "vuex";
import { IUserState } from "./modules/user";
Vue.use(Vuex);
export interface IRootState {
user: IUserState;
}
export default new Vuex.Store<IRootState>({});
store/modules/user.ts
import {
VuexModule,
Module,
Action,
Mutation,
getModule
} from "vuex-module-decorators";
import store from "@/store";
import { UserLogin } from '@/api/login'
export interface IUserState {
token: string;
}
@Module({ dynamic: true, store, name: "user" })
class User extends VuexModule implements IUserState {
public token = sessionStorage.getItem("token") || "";
@Mutation
private SET_TOKEN(token: string) {
sessionStorage.setItem("token", token)
this.token = token;
}
@Mutation
private REMOVE_TOKEN() {
sessionStorage.removeItem('token')
this.token = ""
}
@Action
public async Login(userInfo: { username: string; password: string }) {
const { code, data } = await UserLogin(userInfo)
if (code == 0) {
console.log(data);
this.SET_TOKEN(data.token);
return new Promise((resolve, reject) => {
resolve({ code: 0, message: "登录成功!!!!" })
})
} else {
return new Promise((resolve, reject) => {
resolve({ code: data.code, message: "用户名或密码错误" })
})
}
}
@Action
public async RemoveToken() {
this.REMOVE_TOKEN()
}
}
export const UserModule = getModule(User);
router/index.ts
import Vue from 'vue';
import VueRouter, { RouteConfig } from 'vue-router';
import Home from '../views/Home.vue';
import { UserModule } from '@/store/modules/user'
Vue.use(VueRouter);
const routes: Array<RouteConfig> = [
{
path: '/',
name: 'Home',
component: Home,
},
{
path: "/login",
name: "login",
component: () => import("@/views/login/Login.vue")
},
];
const router = new VueRouter({
mode: 'history',
base: process.env.BASE_URL,
routes,
});
router.beforeEach((to, form, next) => {
const token = UserModule.token;
if (!token) {
if (to.path === "/login") {
next();
return;
}
next({
path: '/login',
query: {
redirect: to.path
}
});
return;
}
if (to.path === "/login") {
next({ path: '/' });
return;
}
next();
})
export default router;
Header.vue
<!--
* @Description:
* @Version: 1.0
* @Autor: solid
* @Date: 2022-04-04 15:49:09
* @LastEditors: solid
* @LastEditTime: 2022-04-04 16:04:09
-->
<template>
<div>{{title}}</div>
</template>
<script lang="ts">
import {Component,Vue,Prop} from "vue-property-decorator"
@Component
export default class Header extends Vue{
@Prop({default:"管理平台"}) private title!:string;
}
</script>
<style>
</style>
login.ts
import { postData } from '@/utils/request'
const userApi = {
Login: '/user/login',
}
export const UserLogin = (data: object) => postData(userApi.Login, data)