实际开发中增加一个新的页面可能就要重新编写路由的问题,导致路由文件每次都要重新编辑,页面较多,修改起来较为复杂。
那么有没有什么办法可以简化这种引入或者导出操作呢?答案是肯定的,下面就为大家介绍一下require.context
以前我们都是通过import 方式引入路由
import HomeView from '../views/HomeView.vue'
Vue.use(VueRouter)
const routes = [
{
path: '/',
name: 'home',
component: HomeView
},
{
path: '/about',
name: 'about',
component: () => import('../views/AboutView.vue')
}
]
这样很蛋疼,因为每加一个页面,可能都要写这么几行,这样有规律的事,是否可以通过自动化完成?
require.context (需要vue-cli3+的版本)
你还可以通过 require.context() 函数来创建自己的 context。
可以给这个函数传入三个参数:一个要搜索的目录,一个标记表示是否还搜索其子目录, 以及一个匹配文件的正则表达式。
Webpack 会在构建中解析代码中的 require.context() 。
语法如下:
require.context(directory, useSubdirectories, regExp)
- directory: 要查找的文件路径
- useSubdirectories: 是否查找子目录
- regExp: 要匹配文件的正则
示例:
require.context('./test', false, /\.test\.js$/);
//(创建出)一个 context,其中文件来自 test 目录,request 以 `.test.js` 结尾。
1.在router文件下随便创建autoRouter.js文件
let routerArr = []
//查找views目录,以.vue结尾的文件,查找子目录
const contexts = require.context('../views/', true, /\.vue$/)
contexts.keys().forEach(value => {
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(`@/views${componentLocation}`)
})
})
export default routerArr
2.在router文件下index.js文件中引入autoRouter.js文件
import Vue from 'vue'
import VueRouter from 'vue-router'
//引入刚刚写的autoRouter.js文件
import routerArr from './autoRouter.js'
Vue.use(VueRouter)
const routes = [
//这里是其他手动写的路由
]
const router = new VueRouter({
mode: 'history',
//这里进行路由合并
routes:[...routes,...routerArr]
})
export default router
3.完成了,后面在views里面新建页面,就不要手动写路由了。
总结
我们可以通过require.context可以自动化引入文件。
其实我们不单单局限于组件,路由, 所有模块文件都是通用的。
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/188406.html