首页前端开发JavaScriptvue3.0路由自动导入的方法实例

vue3.0路由自动导入的方法实例

时间2024-02-01 08:41:03发布访客分类JavaScript浏览322
导读:收集整理的这篇文章主要介绍了vue3.0路由自动导入的方法实例,觉得挺不错的,现在分享给大家,也给大家做个参考。 一、前提我们使用的是require.context方法导入,在vITe创...
收集整理的这篇文章主要介绍了vue3.0路由自动导入的方法实例,觉得挺不错的,现在分享给大家,也给大家做个参考。

一、前提

我们使用的是require.context方法导入,在vITe创建的项目内使用会报错"require not found",所以必须用webpack创建项目。或者有大能可以说说vite怎么解决这个问题。

二、规则

我们使用的规则是,搜索src/views/路径下的所有目录和子目录,搜索文件名叫做"index.vue"的文件,使用上级目录的名字作为组件名,进行注册。结构如下:

和公共组件注册一样,我们只注册index.vue组件,其他名称的组件不进行注册。

三、导入

// src/router/index.tsimport {
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.lengthjieguob.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;
    icanshu.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;
    icanshu.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: ArrayRouteRecordRaw>
 = [    {
            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

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

总结

到此这篇关于vue3.0路由自动导入的文章就介绍到这了,更多相关vue3.0路由自动导入内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

您可能感兴趣的文章:
  • vue3.0 CLI - 3.2 路由的初级使用教程
  • vue2/vue3路由权限管理的方法实例
  • Vue3使用路由VueRouter4的简单示例

声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!

vue使用教程"

若转载请注明出处: vue3.0路由自动导入的方法实例
本文地址: https://pptw.com/jishu/595173.html
JS数组降维的几种方法详解 vue3.0公共组件自动导入的方法实例

游客 回复需填写必要信息