登錄
表單驗證用戶名與密碼,發送登錄請求
login() {
// 數據驗證
this.$refs.loginFormRef.validate(async valid => {
// 驗證不通過
if (!valid) return
// 數據請求
const { data: res } = await this.$https.post('login', this.loginForm)
// 登錄失敗
if (res.meta.status !== 200) return this.$message.error('登錄失敗!')
// 登錄成功
this.$message.success('登錄成功!')
// 緩存token
window.sessionStorage.setItem('token', res.data.token)
// 跳轉主頁面
this.$router.push('/home')
})
}
路由與路由守衛
通過導航守衛判斷用戶是否登錄
// 路由配置
const router = new VueRouter({
routes: [
{ path: '/', redirect: '/login' },
{ path: '/login', component: login },
{ path: '/home', component: home }
]
})
// 掛載路由守衛,驗證token是否已存在
router.beforeEach((to, from, next) => {
if (to.path === '/login') return next()
const tokenStr = window.sessionStorage.getItem('token')
if (!tokenStr) return next('/login')
next()
})
退出登錄
刪除token,跳到登錄頁
logout() {
window.sessionStorage.clear()
this.$router.push('/login')
}
通過接口獲取數據
通過axios請求攔截器添加token,保證擁有獲取數據的權限
// main.js中,axios請求攔截器
axios.interceptors.request.use(config => {
// 為請求頭對象添加token驗證的Authorization字段
config.headers.Authorization = window.sessionStorage.getItem('token')
return config
})