vue3.0路由自动导入

该博客介绍了如何在Webpack和Vite项目中自动化注册基于`index.vue`的组件,并构建路由。在Webpack项目中,通过`require.context`实现动态导入,根据文件路径生成并排序路由。而在Vite2中,利用`import.meta.globEager`进行自动化注册,同样处理了路由层级和参数。整个过程避免了手动注册的繁琐步骤。

一、前提

我们使用的是require.context方法导入,在vite创建的项目内使用会报错"require not found",所以必须用webpack创建项目。或者有大能可以说说vite怎么解决这个问题。
2021年5月17日,经过几天测试,vite2的自动导入搞定了

二、规则

我们使用的规则是,搜索src/views/路径下的所有目录和子目录,搜索文件名叫做"index.vue"的文件,使用上级目录的名字作为组件名,进行注册。结构如下:
在这里插入图片描述
和公共组件注册一样,我们只注册index.vue组件,其他名称的组件不进行注册。

三、webpack项目导入

// 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

这样,只需要根据规则创建组件,就会被自动注册到路由里面。免去手动注册的繁琐操作。

四、vite2项目导入

import {createRouter, createWebHashHistory, createWebHistory, Router, RouteRecordRaw} from 'vue-router'
import daxie from "@/util/upper"
import {isMainThread} from "worker_threads";
// 路由自动化注册
const routerList:any = []
// 第一层的都是特殊用途的组件,例如404.vue等,手动输入到router里面了
// 第二层
const modulesFiles1:any = import.meta.globEager('../views/*/index.vue')
const modulesname1  = Object.keys(modulesFiles1).filter((item:any)=>true)
modulesname1.forEach((item:string)=>{
    const name = item.split("/")[2]
    const canshu = modulesFiles1[item].default.canshu || ""
    // 如果有参数
    if(canshu){
        let casnhulist = ""
        canshu.forEach((item:string)=>{
            casnhulist = casnhulist + "/:" + item
        })
        routerList.push({
            name:daxie(name),
            path:"/" + name + canshu,
            component:()=>import(`../views/${name}/index.vue`),
            children:[],
        })
    }else {
        // 如果没有参数
        routerList.push({
            name: daxie(name),
            path: "/" + name,
            component: () => import(`../views/${name}/index.vue`),
            children: [],
        })
    }
})
// 第三层
const modulesFiles2:any = import.meta.globEager('../views/*/*/index.vue')
const modulesname2  = Object.keys(modulesFiles2).filter((item:any)=>true)
modulesname2.forEach((item:string)=>{
    const namelist = item.split("/")
    const name = namelist[3]
    const parentname = namelist[2]
    const canshu = modulesFiles2[item].default.canshu || ""
    routerList.forEach((item:any)=>{
        if(item.name == daxie(parentname)){
            // 如果有参数
            if(canshu){
                let casnhulist = ""
                canshu.forEach((item:string)=>{
                    casnhulist = casnhulist + "/:" + item
                })
                item.children.push({
                    name:daxie(name),
                    path:"/" + name + casnhulist,
                    component:()=>import(`../views/${parentname}/${name}/index.vue`),
                    children:[],
                })
            }else{
                // 没有参数
                item.children.push({
                    name:daxie(name),
                    path:"/" + name,
                    component:()=>import(`../views/${parentname}/${name}/index.vue`),
                    children:[],
                })
            }
        }
    })
})
// 如果有第四层,就再加一个,真是又臭又长啊
console.log(routerList,"kankan")
const routes: Array<RouteRecordRaw> = [
    {
        path:"/",
        redirect:"/login",
    },
    ...routerList,
    {
        path: '/404',
        name: '404',
        component: () => import('@/views/404.vue')
    },
    {
        path: '/:pathMatch(.*)',
        redirect: '/404'
    },
]

console.log(routes,"路由表")

const router = createRouter({
    history: createWebHistory(),
    // history: createWebHashHistory(),
    routes
})
// 在VUE中路由遇到Error: Avoided redundant navigation to current location:报错显示是路由重复
const originalPush = router.push
router.push = function push(location) {
    return originalPush.call(this, location).catch(err => err)
}

export default router

### Vue 3.0 中的路由配置 #### 创建 Vue Router 实例 为了在 Vue 3.0 应用程序中设置路由,首先需要安装 `vue-router`。可以通过 npm 或 yarn 来完成这一步骤。 ```bash npm install vue-router@next ``` 接着,在项目中创建一个新的文件来定义路由器实例: ```javascript // src/router/index.js import { createRouter, createWebHistory } from &#39;vue-router&#39; import Home from &#39;../views/Home.vue&#39; const routes = [ { path: &#39;/&#39;, name: &#39;Home&#39;, component: Home, }, ] const router = createRouter({ history: createWebHistory(), routes, }) export default router; ``` 这段代码展示了如何通过导入必要的模块并指定路径映射到视图组件的方式来初始化一个简单的路由表[^1]。 #### 配置主应用以使用路由 为了让整个应用程序识别这些路由规则,还需要修改入口文件 (`main.js`) 和根组件 (通常是 App.vue),以便它们可以加载和渲染不同的页面内容。 ```javascript // main.js import { createApp } from &#39;vue&#39;; import App from &#39;./App.vue&#39;; import router from &#39;./router&#39;; createApp(App).use(router).mount(&#39;#app&#39;); ``` 以上操作使得当浏览器访问特定 URL 时,对应的组件会被动态加载并显示出来。 #### 添加导航链接 最后,在模板里添加一些 `<router-link>` 标签用于实现页面间的跳转功能;同时利用 `<router-view>` 占位符让不同路由下的组件得以呈现。 ```html <!-- App.vue --> <template> <div id="nav"> <router-link to="/">Home</router-link> | <!-- 更多链接... --> </div> <router-view></router-view> </template> <script setup lang="ts"></script> <style scoped></style> ``` 这样就完成了基本的 Vue 3.0 路由配置过程。
评论 12
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值