溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

vue3.0路由自動(dòng)導(dǎo)入的方法實(shí)例

發(fā)布時(shí)間:2021-04-09 11:04:14 來源:億速云 閱讀:186 作者:啵贊 欄目:開發(fā)技術(shù)

這篇文章主要介紹“vue3.0路由自動(dòng)導(dǎo)入的方法實(shí)例”,在日常操作中,相信很多人在vue3.0路由自動(dòng)導(dǎo)入的方法實(shí)例問題上存在疑惑,小編查閱了各式資料,整理出簡單好用的操作方法,希望對(duì)大家解答”vue3.0路由自動(dòng)導(dǎo)入的方法實(shí)例”的疑惑有所幫助!接下來,請(qǐng)跟著小編一起來學(xué)習(xí)吧!

為什么要使用Vue

Vue是一款友好的、多用途且高性能的JavaScript框架,使用vue可以創(chuàng)建可維護(hù)性和可測試性更強(qiáng)的代碼庫,Vue允許可以將一個(gè)網(wǎng)頁分割成可復(fù)用的組件,每個(gè)組件都包含屬于自己的HTML、CSS、JavaScript,以用來渲染網(wǎng)頁中相應(yīng)的地方,所以越來越多的前端開發(fā)者使用vue。

一、前提

我們使用的是require.context方法導(dǎo)入,在vite創(chuàng)建的項(xiàng)目內(nèi)使用會(huì)報(bào)錯(cuò)"require not found",所以必須用webpack創(chuàng)建項(xiàng)目?;蛘哂写竽芸梢哉f說vite怎么解決這個(gè)問題。

二、規(guī)則

我們使用的規(guī)則是,搜索src/views/路徑下的所有目錄和子目錄,搜索文件名叫做"index.vue"的文件,使用上級(jí)目錄的名字作為組件名,進(jìn)行注冊(cè)。結(jié)構(gòu)如下:

vue3.0路由自動(dòng)導(dǎo)入的方法實(shí)例

和公共組件注冊(cè)一樣,我們只注冊(cè)index.vue組件,其他名稱的組件不進(jìn)行注冊(cè)。

三、導(dǎo)入

// src/router/index.ts

import {createRouter, createWebHashHistory, createWebHistory, RouteRecordRaw} from 'vue-router'
import store from "@/store";
import daxie from "@/util/upper";		// 引入一個(gè)方法,將字符串的首字母進(jìn)行大寫,我習(xí)慣將pathname首字母大寫

// 路由自動(dòng)化注冊(cè)
const routerList:any = []
const requireComponent = require.context('@/views', true, /index.vue$/) // 找到views路徑下的所有文件
const dynamic_route = requireComponent.keys().filter(fileName => {
    return true
})
// 現(xiàn)在文件數(shù)組是亂序的,我們首先進(jìn)行排序,父級(jí)路由在前面,如果是子級(jí)路由在前面,結(jié)果父級(jí)理由還沒有創(chuàng)建,就會(huì)報(bào)錯(cuò)
// 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)
    // 組件可以隨意添加任何屬性,目前添加一個(gè)canshu屬性,是一個(gè)數(shù)組,里面存放著需要的動(dòng)態(tài)參數(shù)
    // console.log(componentConfig.default,"組件配置2")
    // 每一層都需要手動(dòng)指定,只做三層吧
    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])){
                // 判斷組件是否需要參數(shù)
                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])){
                        // 判斷是不是需要參數(shù)
                        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'
    },
]
// 注意順序,根據(jù)最新的路由匹配規(guī)則,404頁面必須在最后,
console.log(routes,"查看路由表內(nèi)容")

const router = createRouter({
    history: createWebHistory(),
    // history: createWebHashHistory(),
    routes
})

export default router

這樣,只需要根據(jù)規(guī)則創(chuàng)建組件,就會(huì)被自動(dòng)注冊(cè)到路由里面。免去手動(dòng)注冊(cè)的繁瑣操作。

總結(jié)

到此,關(guān)于“vue3.0路由自動(dòng)導(dǎo)入的方法實(shí)例”的學(xué)習(xí)就結(jié)束了,希望能夠解決大家的疑惑。理論與實(shí)踐的搭配能更好的幫助大家學(xué)習(xí),快去試試吧!若想繼續(xù)學(xué)習(xí)更多相關(guān)知識(shí),請(qǐng)繼續(xù)關(guān)注億速云網(wǎng)站,小編會(huì)繼續(xù)努力為大家?guī)砀鄬?shí)用的文章!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI