一.完成登录功能
1.表单重置
<el-form ref="loginForm"></el-form>
resetForm() {
this.$refs.loginForm.resetFields()
}
2.表单校验
async login(username,password) {
try {
this.$refs.loginForm.validate();
try {
const result = await this.$axios.login(this.loginForm);
console.log(this.loginForm);
this.$router.push('/user/index')
} catch (e) {
this.$message.error(e, { delay: 1000 });
}
} catch (e) {
this.$message.error(e);
}
},
3.封装接口地址
axios.defaults.baseURL = 'https://www.liulongbin.top:8888/api/private/v1/';
4.封装axios,拦截器和项目接口
1.axios封装和拦截器
import axios from 'axios';
axios.defaults.baseURL = 'https://www.liulongbin.top:8888/api/private/v1/';
axios.interceptors.request.use(config => {
config.headers['Authorization'] = sessionStorage.getItem('token');
return config;
})
axios.interceptors.response.use(config => {
console.log(config)
const { data: { meta: { status, msg }, data: data1 } } = config;
switch (status) {
case 200:
case 201:
case 204:
data1 && data1.token && sessionStorage.setItem('token', data1.token);
return Promise.resolve({ data1, msg });
default:
return Promise.reject(msg);
}
})
2.封装项目接口
export default {
login({username,password}){
return axios.get('login',{
username,password
})
},
}
3.路由守卫(登录)
router.beforeEach((to,from,next)=>{
if(to.path == '/admin/index'){
if(sessionStorage.getItem('token') == null){
alert('请先登录');
next('/admin/login')
}else{
next()
}
}
if(to.path == '/admin/login'){
if(sessionStorage.getItem('token') !== null){
next('/admin/index')
}else{
next()
}
}
})