灯塔建设网站,网站分成比例系统怎么做,liunx wordpress 搭建,wordpress 标签分类目录
一、自动引入组件
1、语法
2、使用
2.1、在compoents文件下随便创建index.js文件
2.2、mian.js引入该js
二、自动生成路由
1、示例#xff1a;
2、使用
2.1、在router文件下随便创建autoRouter.js文件
2.2、在router文件下index.js文件中引入autoRouter.js文件…目录
一、自动引入组件
1、语法
2、使用
2.1、在compoents文件下随便创建index.js文件
2.2、mian.js引入该js
二、自动生成路由
1、示例
2、使用
2.1、在router文件下随便创建autoRouter.js文件
2.2、在router文件下index.js文件中引入autoRouter.js文件
三、总结 一、自动引入组件
我们项目开发中经常需要import或者export各种模块那么有没有什么办法可以简化这种引入或者导出操作呢答案是肯定的下面就为大家介绍一下require.context
require.context 是 webpack 提供的一个 API用于创建 context即一组具有相同上下文的模块。
使用 require.context 可以方便地加载多个模块并且可以灵活地控制模块的加载顺序和依赖关系。 以前我们都是通过import 方式引入组件
import A from components/A
import B from components/B
import C from components/C
import D from components/D
这样很蛋疼因为每加一个组件可能都要写这么一句这样有规律的事是否可以通过自动化完成? require.context (需要vue-cli3的版本) 1、语法
require.context(directory, useSubdirectories, regExp) directory: 要查找的文件路径useSubdirectories: 是否查找子目录regExp: 要匹配文件的正则 2、使用
2.1、在compoents文件下随便创建index.js文件
const requireComponent require.context(./, true, /\.vue$/)
const install (Vue) {if (install.installed) returninstall.installedrequireComponent.keys().forEach(element {const config requireComponent(element)if (config config.default.name) {const componentName config.default.nameVue.component(componentName, config.default || config)}});
}if (typeof window ! undefined window.Vue) {install(window.Vue)
}export default {install
}
2.2、mian.js引入该js
import install from ./compoents
Vue.use(install)
3.3、这样在其他页面使用组件的时候就不用再引用和注册了。直接使用就可以了。
比如直接这样使用就可以了不用在import引入不用components注册了。
templateHelloWorld/HelloWorld
/template
二、自动生成路由
实际开发中增加一个新的页面可能就要重新编写路由的问题导致路由文件每次都要重新编辑页面较多修改起来较为复杂。
那么有没有什么办法可以简化这种引入或者导出操作呢答案是肯定的下面就为大家介绍一下require.context
以前我们都是通过import 方式引入路由
import HomeView from ../views/HomeView.vueVue.use(VueRouter)const routes [{path: /,name: home,component: HomeView},{path: /about,name: about,component: () import(../views/AboutView.vue)}
]
1、示例
require.context(./test, false, /\.test\.js$/);
//创建出一个 context其中文件来自 test 目录request 以 .test.js 结尾。
2、使用
2.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.2、在router文件下index.js文件中引入autoRouter.js文件
import Vue from vue
import VueRouter from vue-router//引入刚刚写的autoRouter.js文件
import routerArr from ./autoRouter.jsVue.use(VueRouter)
const routes [//这里是其他手动写的路由
]const router new VueRouter({mode: history,//这里进行路由合并routes:[...routes,...routerArr]
})export default router 完成了后面在views里面新建页面就不要手动写路由了。 三、总结
我们可以通过require.context可以自动化引入文件。 其实我们不单单局限于组件路由内 所有模块文件都是通用的 例如路由 接口封装模块都是可以使用的。