Skip to content

自动生成路由

在使用vue-router时,配置路由需要重复的写相同的部分,可以利用一些约定来通过代码自动生成

js
import { createRouter, createWebHashHistory } from 'vue-router'
// 获取views下的指定后缀名的所有文件
const views = require.context('@/views', true, /.vue$/).keys()
// 遍历生成routes
const routes = views.map( item => {
    const path = item.slice(1,-10) || '/'
    const name = path.slice(1).split('/').join('-') || 'index'
    return {
        path,
        name,
        component: () => import(`@/views${item.slice(1)}`)
    }
})

export default createRouter({
    history: createWebHashHistory('/'),
    routes: routes
})
import { createRouter, createWebHashHistory } from 'vue-router'
// 获取views下的指定后缀名的所有文件
const views = require.context('@/views', true, /.vue$/).keys()
// 遍历生成routes
const routes = views.map( item => {
    const path = item.slice(1,-10) || '/'
    const name = path.slice(1).split('/').join('-') || 'index'
    return {
        path,
        name,
        component: () => import(`@/views${item.slice(1)}`)
    }
})

export default createRouter({
    history: createWebHashHistory('/'),
    routes: routes
})