router.beforeEach((to, from, next) => { if (to.meta.requireAuth) { // 需要權限,進一步進行判斷 if (store.state.login.token) { // 通過vuex state獲取當前的token是否存在 next(); } else { //如果沒有權限,重定向到登錄頁,進行登錄 next({ path: '/login', // query: {redirect: to.fullPath} // 將跳轉的路由path作為參數,登錄成功后跳轉到該路由 }) } } else { //不需要權限 直接跳轉 next(); } })
{ path: '/user', name: '用戶頁', component: User, meta: { requireAuth: true, // 添加該字段,表示進入這個路由是需要登錄才能進入的 }, }
