基礎(chǔ)組件的自動化全局注冊

原文鏈接
// 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
// 全局導(dǎo)入組件文件
const requireComponent = require.context(
  // Look for files in the current directory
  // 根據(jù)路徑查找當(dāng)前目錄中的文件
  '.',
  // Do not look in subdirectories
  // 是否查詢其子目錄
  false,
  // Only include "_base-" prefixed .vue files
  // 匹配組件文件名的正式表達(dá)式,示例:_base-button.vue
  /_base-[\w-]+\.vue$/
)

// For each matching file name...
// 循環(huán)所有匹配的文件名
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'
  // 這一段可根據(jù)實際組件名進(jìn)行修改
  const componentName = fileName
    // Remove the "./_" from the beginning
    // 去除名稱中的 './_'
    .replace(/^\.\/_/, '')
    // Remove the file extension from the end
    // 去除擴(kuò)展名
    .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 文件中
  • 使用:在某頁面中直接 <base-button /> 即可
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容