先安装axios模块
npm i axios
image.png
例子
//表单登录预验证 // validate是elementui里面form表单的一个函数,是再次验证表单规则,参数是一个函数,携带一个valid形参,返回是否合法
login() {
this.$refs.loginFormRef.validate(async valid => {
// valid是个布尔值,合法则是true
// console.log(valid);
// 不合法
if(!valid) return;
// console.log(this);
// console.log(this);
// 合法
// const {data: res} = await this.axios.post('login',this.loginForm);
// // console.log(res);
// //登录失败情况
// if(res.meta.status !== 200) return console.log('登录失败');
// console.log('登录成功');
//axios
await this.$http
.post('login',this.loginForm)
.then(res=>{
//登录成功的回调
console.log(res.data);
})
.catch(err=>{
console.log(err);
})
});
}
//自己写axios
await this.$http
.post('login',this.loginForm)
.then(res=>{
//登录成功的回调
console.log(res);
if(res.data.meta.status !== 200) {
//console.log(res.meta.status);是错误的
return this.$message.error('登录失败');
}
return this.$message.success('登录成功');
})
.catch(err=>{
console.log(err);
})
在登录成功之后就要写登录之后的操作行为
1.登录成功后的token,保存到客户端的sessionStorage 中//session是无法跨窗口使用的
1.1 项目中除了登录之外的其他API接口,必须在登录之后才能访问
1.2 token 只应该在当前网站打开期间生效,所以将token 保存在sessionStorage中
window.sessionStorage.setItem('token',res.data.data.token);
2.通过编程式导航跳转到后台主页,路由地址是 /home
this.$router.push() 的用法
1、作用:this.$router.push() 可以通过修改url实现路由跳转。
2、push 后面可以是对象,也可以是字符串:
// 字符串
this.$router.push('/home/first')
// 对象
this.$router.push({ path: '/home/first' })
// 命名的路由
this.$router.push({ name: 'home', params: { userId: wise }})
网友评论