基础组件的自动化全局注册

原文链接
// Globally register all base components for convenience, because they
// will be used very frequently. Components are registered using the
// PascalCased version of their file name.

import Vue from 'vue'

// https://webpack.js.org/guides/dependency-management/#require-context
// 全局导入组件文件
const requireComponent = require.context(
  // Look for files in the current directory
  // 根据路径查找当前目录中的文件
  '.',
  // Do not look in subdirectories
  // 是否查询其子目录
  false,
  // Only include "_base-" prefixed .vue files
  // 匹配组件文件名的正式表达式,示例:_base-button.vue
  /_base-[\w-]+\.vue$/
)

// For each matching file name...
// 循环所有匹配的文件名
requireComponent.keys().forEach((fileName) => {
  // Get the component config
  // 获取组件配置
  const componentConfig = requireComponent(fileName)
  // Get the PascalCase version of the component name
  // 获取 PascalCase 形式的组件名,ex: './_base-button.vue'
  // 这一段可根据实际组件名进行修改
  const componentName = fileName
    // Remove the "./_" from the beginning
    // 去除名称中的 './_'
    .replace(/^\.\/_/, '')
    // Remove the file extension from the end
    // 去除扩展名
    .replace(/\.\w+$/, '')
    // Split up kebabs
    // 以 '-' 分割,ex:['base', 'button']
    .split('-')
    // Upper case
    // 首字母大写
    .map((kebab) => kebab.charAt(0).toUpperCase() + kebab.slice(1))
    // Concatenated
    // 最后拼接好,ex:BaseButton
    .join('')

  // Globally register the component
  // 全局注册组件
  Vue.component(componentName, componentConfig.default || componentConfig)
})

其他:

  • 这段代码须放在 new Vue() 之前,推荐放在 man.js 文件中
  • 使用:在某页面中直接 即可

你可能感兴趣的:(基础组件的自动化全局注册)