原文鏈接
// 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ù)實(shí)際組件名進(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
// 全局注冊(cè)組件
Vue.component(componentName, componentConfig.default || componentConfig)
})
其他:
- 這段代碼須放在 new Vue() 之前巨税,推薦放在 man.js 文件中
- 使用:在某頁面中直接 <base-button /> 即可