文件目錄如下:
commenComponents 文件夾下 index.js代碼如下:
// 一次引入終身受用
/**
* require.context()參數的意義
* arg1.在哪裏找
* arg2.是否要找子集
* arg3.以什麼爲規則來找
*/
const requireComponent = require.context('./', true, /\.vue$/)
const install = (Vue) => {
// 如果組件被註冊就返回,沒有就註冊
if (install.installed) return
install.installed = true
requireComponent.keys().forEach(filename => {
// filename 文件
// 第i個組件
const config = requireComponent(filename)
// 組件名
const componentName = config.default.name
console.log(componentName, '================= 組件名') // 輸出依次是Test LineChart PieChart
// 循環註冊組件
Vue.component(componentName, config.default || config)
})
}
// 確保是正常環境
// 在做插件的情況下進行判斷
// if (typeof window !== 'undefined' && window.Vue) {
// install(window.Vue)
// }
export default {
install
}