為了防止用戶未登錄直接修改路徑來訪問頁面,解決辦法:
在main.js文件中加入以下代碼:
// 路由攔截 router.beforeEach((to, from, next) => { if (to.meta.requireAuth) { //判斷該路由是否需要登錄 if (store.state.Token) { //vuex獲取當前token是否存在 next(); } else { Message({ showClose: true, message: '請先登錄!', type: "warning" }); next({ path: '/login', query: { redirect: to.fullPath } //將跳轉的路由path作為參數,登錄成功后跳轉該路由 }) } } else { //無需登錄直接跳轉頁面 next(); } })
在需要攔截的路由中添加: