vue2 webpack 在路由index中定义 在页面中直接this.$router可以访问所有的路由
import Vue from 'vue'
import Router from 'vue-router'
Vue.use(Router)
let arr={ path:'',
name:'',children:[]}
let routerArr = []
// 匹配所有的页面,contexts即为匹配的信息
const contexts = require.context('../views', true, /\.vue$/)
console.log(contexts.keys());
contexts.keys().forEach((value,index) => {
let a=value.split('/')
a.shift()
console.log(a);
// const component = contexts(value)
// 判断是否存在 $dynamicRoute 属性 存在才作为路由
// if (component.default.$dynamicRoute) {
const path = value.substr(value.indexOf('/'), value.lastIndexOf('.') - 1)
const componentLocation = value.substr(value.indexOf('.') + 1, value.lastIndexOf('.') - 1)
const componentName = componentLocation.substr(componentLocation.lastIndexOf('/') + 1)
routerArr.push({
path: path,
name: componentName,
component: () => import(/* webpackChunkName: "alarm" */ `../views${componentLocation}`),
meta:{
id:a.length,
sortid:index,
title:a
}
})
})
function pathTreeGenerator(value,routerArr) {
}
const router = new Router({
mode: 'history',
base: process.env.BASE_URL,
routes:routerArr
})
console.log(router);
export default router
页面设置,设置 $dynamicRoute是为了区别页面是否要注册路由
<template>
<div class="about">
<h1>This is an about page</h1>
</div>
</template>
<script>
export default{
$dynamicRoute: {
name: "about",
path: "about",
meta: { title: 33 },
},
}
</script>
vue3 vite 与vue2类似 不过对于不注册路由的页面还需要研究,可以自行定义页面属性去判断
import { createRouter, RouteRecordRaw, createWebHistory,createWebHashHistory } from "vue-router";
import user from "./user.ts";
// const routes: Array<RouteRecordRaw> = [
// ];
// 路由配置
const pages = import.meta.glob('../views/**/page.js', {
eager: true,
import: 'default'
})
const pageComps = import.meta.glob('../views/**/index.vue')
let routes=Object.entries(pages).map(([path,meta])=>{
let pagepath=path
let compath=pagepath.replace('page.js','index.vue')
path= path.replace('../views','').replace('/page.js','')||'/'
let name=path.split('/').filter(Boolean).join('-')||'index'
return {
path,
name,
component:pageComps[compath],
meta
}
}
)
routes.push(...user)
const router = createRouter({
//hash历史模式
history: createWebHashHistory(),
routes:routes,
});
console.log(router);
export default router;