Vue動(dòng)態(tài)路由

動(dòng)態(tài)路由的作用

  • 權(quán)限管理(主要原因)
  • 路由多的時(shí)候,手動(dòng)掛載繁瑣
第一步先封裝一個(gè)處理獲取到的路由數(shù)據(jù)的方法(根據(jù)后端數(shù)據(jù)格式,具體情況具體分析)本文章的數(shù)據(jù)格式為
[{
    nav: "",
    comp_path: '',
    navList: [{
        title: "",
        name: '',
        path: '',
        component: ''
    }]
}]

-- 在src文件夾中創(chuàng)建一個(gè)untils文件夾,并創(chuàng)建一個(gè)js文件,在此文件中封裝處理數(shù)據(jù)以及動(dòng)態(tài)掛載路由的方法

//引入獲取側(cè)邊欄路由數(shù)據(jù)的接口
import { aside } from '../api/admin';
//引入路由
import router from '@/router/index';


//動(dòng)態(tài)掛在路由的方法
async function getChildrenpath() {
    //此數(shù)組用來(lái)保存處理好的路由數(shù)據(jù)
    const routerList = [];
    //發(fā)送請(qǐng)求獲取路由列表
    let list_ = await aside();
    //將路由列表存到vuex中
    // console.log(list_)
    //生成子路由數(shù)組
    list_.forEach(item => {
        setChild(item, routerList, '')
    })
    //父路由
    let rou = {
        name: 'home',
        path: '/',
        component: () => import("@/views/Index.vue"),
        children: routerList
    }
    // console.log(rou)
    //掛載所有路由
    router.addRoute(rou)
}



//封裝生成子級(jí)路由數(shù)組的方法
function setChild(item, routerList, rootPath) {
    // item 循環(huán)的元素
    //routerList 子路由數(shù)組列表
    //rootPath 子路由組件 所在的父文件夾路徑
    if (item.navList != null && item.navList != [] && item.navList.length > 0) {
        //說(shuō)明有子級(jí)
        item.navList.forEach(node => {
            //繼續(xù)判斷子級(jí)有沒(méi)有子級(jí)
            setChild(node, routerList, item.comp_path)
        })
    } else {
        //沒(méi)有下一層 說(shuō)明這是一個(gè)路由
        let rou = {
            name: item.name,
            path: item.path,
            component: () => import('../components' + rootPath + item.component)
        }
        routerList.push(rou)
    }
}

//導(dǎo)出動(dòng)態(tài)掛載路由的方法
export default {
    getChildrenpath
}
在合適的時(shí)機(jī)調(diào)用方法動(dòng)態(tài)掛載路由,當(dāng)首次訪問(wèn)路由之前掛載最合適,所以本文章采取在全局前置路由守衛(wèi)中調(diào)用函數(shù),
import un from '@/untils/routerUntils'
let registerRouteFresh = true;//路由數(shù)據(jù)是否還沒(méi)有動(dòng)態(tài)加載過(guò)
router.beforeEach(async (to, from, next) => {
  let isLogin=true;//模擬數(shù)據(jù)
  if(to.path=='/login'){
    isLogin=false;
  }
  if (isLogin) {
    if (registerRouteFresh) {//還沒(méi)有動(dòng)態(tài)加載過(guò)
      //動(dòng)態(tài)注冊(cè)路由 <----------------------------------------
      await un.getChildrenpath();
      registerRouteFresh = false;//已動(dòng)態(tài)加載過(guò)
      // ...to確保addRoutes操作完成,能夠找到出口路由
      next({ ...to, replace: true });
    } else {
      //已經(jīng)登錄了,不能再打開(kāi)登錄頁(yè)
      to.path === "/login" ? next("/") : next();
    }
  }
  else {
    //未登錄,轉(zhuǎn)向登錄頁(yè)面
    to.path === "/login" ? next() : next("/login");
  }
}
);
?著作權(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),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

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