router.beforeEach((to, from, next) => {
if (to.matched.some(record => record.meta.requireAuth)){ // 判斷該路由是否需要登錄權限
if (token) { // 判斷當前的token是否存在
next();
}
else {
next({
path: '/login',
query: {redirect: to.fullPath} // 將跳轉的路由path作為參數,登錄成功后跳轉到該路由
})
}
}
else {
next();
}
});
在這之前是給路由加一個meta屬性:
{
path: '/index',
meta: {
title: '',
requireAuth: true, // 添加該字段,表示進入這個路由是需要登錄的
},
}