vue require.context全局注册组件的具体实现
|
作用:一个 Webpack 提供的 API 方法,通过函数可以获取一个上下文,通常用来简化大量频繁的引入组件操作。
require.context() 接收三个参数:
- :要查找的目录路径
- :是否查找子目录
- :要匹配的文件正则表达式
- const req = require.context('./component',true,/\.vue$/)
复制代码 过程:require.context() 执行后会返回一个 req 对象,该 req 对象中存在有一个 keys() 方法成员,
keys() 文件路径数组
作用:它会返回一个 require.context() 方法在指定目录下查找到的所有文件路径数组。- const req = require.context('./component',true,/\.vue$/)
- console.log(req.keys())
- // ['./component/SvgIcon.vue','./component/Form/Login.vue','./component/Channel.vue'...]
- req.keys().forEach(item => {
- ...
- })
复制代码 在拿到所有待注册组件的文件路径之后,便可以传给对象本身进行一个解构导出操作。
一、定义2个组件
scr/components/ComponentsA/index.vue- <template>
- <div>A组件</div>
- </template>
- <script>
- export default {
- name: 'ComponentA'
- }
- </script>
复制代码 scr/components/ComponentsB/BBB/BBBB/index.vue- <template>
- <div>B组件</div>
- </template>
- <script>
- export default {
- name: 'ComponentB'
- }
- </script>
复制代码 二、局部使用这两个组件
- <template>
- <div id="app">
- <ComponentA />
- <ComponentB />
- </div>
- </template>
- <script>
- import ComponentA from '@/components/ComponentA'
- import ComponentB from '@/components/ComponentB/BBB/BBBB'
- export default {
- components: { ComponentA, ComponentB }
- }
- </script>
复制代码 三、全局注册组件
如果这2个组件是基础性的组件,项目中好多地方都要用到,可以注册成全局组件
src/requireAllComponents.js- import Vue from 'vue'
- const componentsContext = require.context('@/components', true, /index.vue$/) // true表示递归查找 正则匹配index.vue文件
- componentsContext.keys().forEach(item => {
- const componentConfig = componentsContext(item).default
- Vue.component(componentConfig.name, componentConfig) // 全局注册组件
- })
复制代码 main.js- import './requireAllComponents'
复制代码 此时,便不再需要在每个组件中都引入这种基础组件了
到此这篇关于vue require.context全局注册组件的文章就介绍到这了,更多相关vue require.context全局注册组件内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
来源:https://www.jb51.net/javascript/321032p39.htm
免责声明:由于采集信息均来自互联网,如果侵犯了您的权益,请联系我们【E-Mail:cb@itdo.tech】 我们会及时删除侵权内容,谢谢合作! |
|
|
|
发表于 2024-5-27 14:35:22
举报
回复
分享
|
|
|
|