翼度科技»论坛 编程开发 JavaScript 查看内容

vue require.context全局注册组件的具体实现

8

主题

8

帖子

24

积分

新手上路

Rank: 1

积分
24
​ 作用:一个 Webpack 提供的 API 方法,通过
  1. require.context()
复制代码
函数可以获取一个上下文,通常用来简化大量频繁的引入组件操作。​
require.context() 接收三个参数:

    1. directory
    复制代码
    :要查找的目录路径
    1. isFindSub?
    复制代码
    :是否查找子目录
    1. regExp
    复制代码
    :要匹配的文件正则表达式
  1. const req = require.context('./component',true,/\.vue$/)
复制代码
过程:require.context() 执行后会返回一个 req 对象,该 req 对象中存在有一个 keys() 方法成员,
keys() 文件路径数组
​ 作用:它会返回一个 require.context() 方法在指定目录下查找到的所有文件路径数组。
  1. const req = require.context('./component',true,/\.vue$/)

  2. console.log(req.keys())
  3. // ['./component/SvgIcon.vue','./component/Form/Login.vue','./component/Channel.vue'...]

  4. req.keys().forEach(item => {
  5.     ...
  6. })
复制代码
在拿到所有待注册组件的文件路径之后,便可以传给
  1. req
复制代码
对象本身进行一个
  1. import
复制代码
解构导出操作。

一、定义2个组件

scr/components/ComponentsA/index.vue
  1. <template>
  2.   <div>A组件</div>
  3. </template>
  4. <script>
  5. export default {
  6.   name: 'ComponentA'
  7. }
  8. </script>
复制代码
scr/components/ComponentsB/BBB/BBBB/index.vue
  1. <template>
  2.   <div>B组件</div>
  3. </template>
  4. <script>
  5. export default {
  6.   name: 'ComponentB'
  7. }
  8. </script>
复制代码
二、局部使用这两个组件
  1. <template>
  2.   <div id="app">
  3.     <ComponentA />
  4.     <ComponentB />
  5.   </div>
  6. </template>
  7. <script>
  8. import ComponentA from '@/components/ComponentA'
  9. import ComponentB from '@/components/ComponentB/BBB/BBBB'
  10. export default {
  11.   components: { ComponentA, ComponentB }
  12. }
  13. </script>
复制代码
三、全局注册组件

如果这2个组件是基础性的组件,项目中好多地方都要用到,可以注册成全局组件
src/requireAllComponents.js
  1. import Vue from 'vue'

  2. const componentsContext = require.context('@/components', true, /index.vue$/) // true表示递归查找 正则匹配index.vue文件

  3. componentsContext.keys().forEach(item => {
  4.   const componentConfig = componentsContext(item).default
  5.   Vue.component(componentConfig.name, componentConfig) // 全局注册组件
  6. })
复制代码
main.js
  1. import './requireAllComponents'
复制代码
此时,便不再需要在每个组件中都引入这种基础组件了
到此这篇关于vue require.context全局注册组件的文章就介绍到这了,更多相关vue require.context全局注册组件内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

来源:https://www.jb51.net/javascript/321032p39.htm
免责声明:由于采集信息均来自互联网,如果侵犯了您的权益,请联系我们【E-Mail:cb@itdo.tech】 我们会及时删除侵权内容,谢谢合作!

举报 回复 使用道具