一、前提
我們使用的是require.context方法匯入,在vite創建的專案內使用會報錯"require not found",所以必須用webpack創建專案,或者有大能可以說說vite怎么解決這個問題,
二、規則
我們使用的規則是,搜索src/views/路徑下的所有目錄和子目錄,搜索檔案名叫做"index.vue"的檔案,使用上級目錄的名字作為組件名,進行注冊,結構如下:

和公共組件注冊一樣,我們只注冊index.vue組件,其他名稱的組件不進行注冊,
三、匯入
// src/router/index.ts
import {createRouter, createWebHashHistory, createWebHistory, RouteRecordRaw} from 'vue-router'
import store from "@/store";
import daxie from "@/util/upper"; // 引入一個方法,將字串的首字母進行大寫,我習慣將pathname首字母大寫
// 路由自動化注冊
const routerList:any = []
const requireComponent = require.context('@/views', true, /index.vue$/) // 找到views路徑下的所有檔案
const dynamic_route = requireComponent.keys().filter(fileName => {
return true
})
// 現在檔案陣列是亂序的,我們首先進行排序,父級路由在前面,如果是子級路由在前面,結果父級理由還沒有創建,就會報錯
// console.log(dynamic_route,"排序前")
dynamic_route.sort(function (a,b):number{
const jieguoa:any = a.split("").filter((item:string)=>{
return "/" == item
})
const jieguob:any = b.split("").filter((item:string)=>{
return "/" == item
})
if(jieguoa.length<jieguob.length){return -1}
if(jieguoa.length>jieguob.length){return 1}
return 0
})
// console.log(dynamic_route,"排序后")
dynamic_route.forEach(fileName => {
const path = fileName.replace(".", "")
const namelist = fileName.replace(".", "").replace("index.vue", "").split("/").filter((i:any) => {
return i
})
// 測驗配置
const componentConfig = requireComponent(fileName)
// 組件可以隨意添加任何屬性,目前添加一個canshu屬性,是一個陣列,里面存放著需要的動態引數
// console.log(componentConfig.default,"組件配置2")
// 每一層都需要手動指定,只做三層吧
if(namelist.length == 1){
routerList.push({
path:"/"+ namelist[namelist.length - 1],
name: daxie(namelist[namelist.length-1]),
component:()=>import(`../views${path}`),
children:[],
})
}else if(namelist.length == 2){
routerList.forEach((item:any)=>{
if(item.name == daxie(namelist[0])){
// 判斷組件是否需要引數
const canshu = componentConfig.default.canshu || []
if(canshu){
for (let i=0;i<canshu.length;i++){
canshu[i] = "/:"+canshu[i]
}
item.children.push({
path: namelist[namelist.length-1] + canshu.join(""),
name: daxie(namelist[namelist.length-1]),
component:()=>import(`../views${path}`),
children:[],
})
}else{
item.children.push({
path: namelist[namelist.length-1],
name: daxie(namelist[namelist.length-1]),
component:()=>import(`../views${path}`),
children:[],
})
}
}
})
}else if(namelist.length == 3){
routerList.forEach((item:any)=>{
if(item.name == daxie(namelist[0])){
item.children.forEach((yuansu:any)=>{
if(yuansu.name == daxie(namelist[1])){
// 判斷是不是需要引數
const canshu = componentConfig.default.canshu || []
if(canshu){
for (let i=0;i<canshu.length;i++){
canshu[i] = "/:"+canshu[i]
}
yuansu.children.push({
path: namelist[namelist.length - 1]+canshu.join(""),
name: daxie(namelist[namelist.length-1]),
component:()=>import(`../views${path}`),
})
}else {
yuansu.children.push({
path: namelist[namelist.length - 1],
name: daxie(namelist[namelist.length-1]),
component:()=>import(`../views${path}`),
})
}
}
})
}
})
}
})
const routes: Array<RouteRecordRaw> = [
{
path: '/',
name: 'Home',
component: ()=>import("@/views/shouye/shouye.vue")
},
{
path: '/about',
name: 'About',
component: () => import(/* webpackChunkName: "about" */ '../views/About.vue')
},
...routerList,
{
path: '/404',
name: '404',
component: () => import('@/views/404.vue')
},
{
path: '/:pathMatch(.*)',
redirect: '/404'
},
]
// 注意順序,根據最新的路由匹配規則,404頁面必須在最后,
console.log(routes,"查看路由表內容")
const router = createRouter({
history: createWebHistory(),
// history: createWebHashHistory(),
routes
})
export default router
這樣,只需要根據規則創建組件,就會被自動注冊到路由里面,免去手動注冊的繁瑣操作,
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/273737.html
標籤:其他
上一篇:面試題
