Vue開發(fā)基礎(chǔ)六: 路由守衛(wèi)(判斷登錄狀態(tài))

一、配置路由參數(shù)

在router/index.js 文件中配置路由信息

redirect: 配置路由自動(dòng)跳轉(zhuǎn)
meta.requireAuth: 自定義參數(shù) requireAuth ,標(biāo)志是否需要判斷登錄狀態(tài)(main.js中路由守衛(wèi)將判斷此參數(shù))

import { createRouter, createWebHistory } from 'vue-router'
import LoginView from '../views/LoginView.vue'

const routes = [
  {
    path: "/",
    redirect: "/login"
  },
  {
    path: '/login',
    name: 'login',
    component: LoginView,
  },
  {
    path: '/test',
    name: 'test',
    component: () => import('../views/TestView'),
    meta:{
      requireAuth:false,
    }
  },
  {
    path: '/index',
    name: 'index',
    component: () => import('../views/IndexView'),
    meta:{
      requireAuth:true,
    }
  },
  {
    path: '/news/list',
    name: 'newsList',
    component: () => import('../views/NewsList'),
    meta:{
      requireAuth:true,
    }
  }
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})

export default router

二、main.js 設(shè)置路由守衛(wèi)

import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import { isLogin } from "@/utils/MyFuncs";

// 引入element-plus及其樣式
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'

// 引入ElementPlusIconsVue
import * as ElementPlusIconsVue from '@element-plus/icons-vue'

const app = createApp(App);
app.use(ElementPlus)
    .use(store).use(router).mount('#app')

// 從 @element-plus/icons-vue 中導(dǎo)入所有圖標(biāo)并進(jìn)行全局注冊(cè)
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
    app.component(key, component)
}

// 路由守衛(wèi): 判斷router/index.js中是否配置 requireAuth
router.beforeEach((to, from, next) => {
    // 判斷頁面是否需要檢測(cè)登錄狀態(tài)
    if(to.meta.requireAuth){
        if(!isLogin()){
            next({
                path: "/login",
            })
        }else{
            next();
        }
    }else{
        next();
    }
    // 訪問login頁面時(shí),若已登陸,則直接跳轉(zhuǎn)首頁
    if(to.name == "login"){
        if (isLogin()){
            router.push("/index");
        }
    }
})
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容