vue页面批量引入组件的操作代码

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

vue页面批量引入组件的操作代码

陌上烟雨寒   2022-12-12 我要评论
<template>
  <div>
    <template v-for="(item) in names">
      <component :is="item" :key="item" />
    </template>
  </div>
</template>
<script>
// 可行了
import path from 'path'

// require.context(param1,param2,param3) param1:路径;  param2: 是否搜索子文件夹;  param3: 文件类型,可正则
const files = require.context('@/components/Menu/Dialog', true, /\.vue$/)

const dialogs = {}
const names = []
// 组件导入
files.keys().forEach((key) => {
   /**
    * 
    * 获取vue文件名
    * 法一:用正则表达式匹配 
    * key.replace(/^\.\/(.*)\.\w+$/, '$1')
    * 法一:path.basename获取vue文件名
    * import path from 'path'  
    * path.basename(path[, ext])
	* path.basename() 方法会返回 path 的最后一部分。 尾部的目录分隔符会被忽略。
    **/
    
  // 获取文件名 法一
  // var name = fileName
  //  .split('/')
  //  .pop()
  //  .replace(/\.\w+$/, '');

  // 获取文件名 法二
  const name = path.basename(key, '.vue')
  
  names.push(name)
  dialogs[name] = files(key).default || files(key)
})

export default {
  name: 'Dialogs',
  components: dialogs,
  data() {
    return {
      names: names
    }
  }
}
</script>

<style lang="scss" scoped />

知识点:

require.context(param1,param2,param3)
  • param1:路径;
  • param2: 是否搜索子文件夹;
  • param3: 文件类型,可正则
path.basename(path[, ext])

方法会返回 path 的最后一部分。 尾部的目录分隔符会被忽略

  • path :string
  • ext :string 可选的文件扩展名。
path.basename('/目录1/目录2/文件.html');  // 文件.html
path.basename('/目录1/目录2/文件.html', '.html');  // 文件

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们