1.封装axios请求
2.login.vue组件登入方法请求成功,将token值保存到sessionStorage中
//登入方法
login() {
this.$refs.loginFormRef.validate(async (valid) => {
if (!valid) return
var { data: res } = await this.$http.post('login', this.loginForm)
if (res.meta.status !== 200) return this.$message.error('登入失败')
this.$message.success('登入成功')
// 登入成功把token保存到sessionStorage
window.sessionStorage.setItem('token', res.data.token)
// 通过编程式导航跳转到后台主页,路由是 /home
this.$router.push('/home')
})
}
//退出方法, 清除token
loginOut() {
window.sessionStorage.clear()
this.$route.push('/login')
}
3.在router.js中挂载路由导航守卫
router.beforeEach((to,from,next) => {
if (to.path === '/login') return next()
const tokenStr = window.sessionStorage.getItem('token')
if (!tokenStr) return next('/login')
next()
})