平时咱们普通项目新增页面,一般是
- 步骤一:views内新建页面,
- 步骤二:然后在router中进行关联。
那么有没有办法,省掉步骤二,只用建立文件,路由自动完成?
其实思路也很简单,咱们只要动态获取views文件夹底下所有的vue文件,然后按照特定格式生成路由即可。
首先,咱们看看路由表长啥样?
- component是文件地址
- name/path对应的是文件名
- children则是放置子路由,基本同上
现在咱们得需求明确了,我需要知道到底有哪些页面,以及这些页面的地址名称是啥?
获取所有页面
vite提供了import.meta.glob正好派上用场
const myViews = import.meta.glob('../views/**/*.vue')
console.log("import.meta.glob返回的views数据",myViews)
不难看出,得到的对象中,key是每个页面的相对路径,value则是对应的页面模块 接着,咱们遍历这个对象(Object.keys().map()),生成类似图一的路由表即可。
const rootRoutes = Object.keys(myV).map((path) => {
const name = path.match(/\.\.\/views\/(.*)\.vue$/)[1].toLowerCase();
const routePath = `/${name}`;
if (routePath === '/index') {
return {
path: '/',
name,
redirect: { name: 'Home' },
component: myViews[path],
meta: {
keepAlive: true
},
children: childRoutes
};
}
else {
return {
path: routePath,
name: name,
component: myViews[path]
}
}
})
此前,咱们在meta字段中放了keepAlive,后面渲染组件的时候就可以用上
<router-view v-slot="{ Component }">
<keep-alive>
<component :is="Component" :key="$route.path" v-if="$route.meta.childKeepAlive" />
</keep-alive>
<component :is="Component" :key="$route.path" v-if="!$route.meta.childKeepAlive" />
</router-view>
此处的插槽用法官方文档里面有写,-->传送门<--
至此,按照上述规则配置完,我们新建example页面,只需要建立views/example/example.vue文件,然后就可以通过/example路由直接访问。
举一反三
假设咱们有很多components,这些组件需要全局使用,咱们第一反应就是在vue上全局注册。app.component(名字,组件)
但是,一个一个注册也太低效了,可以考虑写个插件,利用插件获取所有的组件,进行全局注册。
const modules = import.meta.globEager('../components/*/*.vue')
export default {
install(app) {
Object.keys(modules).forEach(componentPath => {
// 获取遍历的当前组件实例对象
let curComponent = modules[componentPath].default
app.component(curComponent.__name, curComponent);
})
}
}
完事,把这个插件引入到main.js然后use一下即可。