token
http:无状态的
cookie:【客户端】记录状态
session:【服务器】记录状态
token:维持状态————存在【跨域】
路由导航守卫
如果用户没有登录,但是直接通过URL访问特定页面,需要重新导航到登录页面。
登录
1.定义路由
2.在暴露路由之前,挂在路由导航守卫
3.暴露路由
to 将要访问的路径 路由对象(包含那么,params, meta等属性)
from 代表从那个路径跳转而来(正要离开的路由对象)
next 是一个函数,表示放行
next() 放行 next('/login') 强制跳转
// 2. 挂载路由导航守卫
router.beforeEach((to, from, next) => {
//
if (to.path === '/login') return next()
// else if (to.path === '/home') return next()
// 获取token
const tokenStr = window.sessionStorage.getItem('token')
if (!tokenStr) return next('/login')
next()
})
退出
按钮绑定退出登录事件.
window.sessionStorage.clear()
// 清空sessionStorage中的token
$router.push('/login')
// 路由重定向到登录页面
async logout() {
const confirmed = await this.$confirm('确定要退出登录吗?', '提示', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning'
}).catch(err => {
return err
})
if (confirmed !== 'confirm') {
return
}
const { data: res } = await this.$http.post('user/logout')
if (res.code === 200) {
this.$message.success('已退出登录')
window.sessionStorage.clear() // 清空sessionStorage中的token
}
this.$router.push('/login')
}