項(xiàng)目中需要有些頁面的接口需要用到token,而token是登錄接口返回存在cookie里面的.肯定沒有登錄前這些接口是不能發(fā)送的.所以需要做一個(gè)登錄攔截.在每一個(gè)頁面去判斷是不是有cookie的存在比較的麻煩,查(chao)了(xi)下百度,將自己做的代碼記錄下:
1:在main.js全局文件中判斷cookie中是否存在token,存在就按照正常的頁面跳轉(zhuǎn),不存在就跳轉(zhuǎn)到登錄界面:
使用了mint-ui中的message-box來提示用戶是否跳轉(zhuǎn)到登錄界面.
router.beforeEach((to, from, next) => {
if (to.matched.some(record => record.meta.requireAuth)) { // 判斷該路由是否需要登錄權(quán)限
if (getCookie('userCookie')) { // 判斷當(dāng)前的token是否存在
// console.log("router.beforeEach進(jìn)入了");
next();
} else {
MessageBox({
title: '溫馨提示',
message: '您沒有登錄,請立即登錄',
showCancelButton: true
}).then(action => {
if (action == 'confirm') {
next({
path: '/login',
query: {
redirect: to.fullPath
} // 將跳轉(zhuǎn)的路由path作為參數(shù),登錄成功后跳轉(zhuǎn)到該路由
})
}
});
}
} else {
next();
}
});
2:在路由文件中,配置路由:
哪個(gè)路由跳轉(zhuǎn)前需要登錄的,配置下meta下的requireAuth的為true就ok了.
{
path: "/withdrawal",//提現(xiàn)
name : "withdrawal",
component : Withdrawal,
meta: {
title: '',
requireAuth: true, // 添加該字段,表示進(jìn)入這個(gè)路由是需要登錄的
},
},
3:router.beforeEach的理解:
沒(bu)有(xiang)時(shí)(xie)間(le),回去再來寫啦~~~