侧边栏壁纸
博主头像
suringYu

走走停停

  • 累计撰写 50 篇文章
  • 累计创建 18 个标签
  • 累计收到 3 条评论

目 录CONTENT

文章目录
vue

vue2根据文件夹动态生成路由

suringYu
2023-03-24 / 0 评论 / 0 点赞 / 393 阅读 / 315 字

需求场景

在开发中导入原型静态页面的时候(只是为了方便点查看原型),发现有很多页面,要配置很多路由,又不想一个个引入,再一个个的配置,还有层级关系如demo/modular1/spte1需要配置,这样的话就会非常繁琐

实现代码

import Vue from 'vue'
import Router from 'vue-router'

Vue.use(Router)
const router = new Router({
    mode: 'history',
    base: 'demo',
    routes: []
})

const requireComponent = require.context('@/views', true, /\.vue$/)

requireComponent.keys().forEach(filePath => {
    const component = requireComponent(filePath).default
    const filePathSegments = filePath.split('/')

    let routePath = ''
    let parent = router.options.routes

    // 遍历路径分段,生成路由结构
    filePathSegments.forEach((segment, index) => {
        // 忽略第一级路径
        if (index === 0) {
            return
        }

        // 获取组件名称
        const componentName = segment.replace(/\.\w+$/, '')

        // 获取路由地址
        const path = `${routePath}/${componentName.toLowerCase()}`

        // 查找现有的同级路由
        let child = parent.find(route => route.path === path)

        // 如果同级路由不存在,则创建一个新的路由
        if (!child) {
            child = {
                path,
                component: index === filePathSegments.length - 1 ? component : { render: h => h('router-view') },
                children: []
            }
            parent.push(child)
        }

        // 将子路由添加到父路由中
        parent = child.children

        // 更新当前路径
        routePath = child.path
    })
})
router.addRoutes([
    // 其他路径的路由或者404错误页面等
    ...router.options.routes
])
0

评论区