組件是我們非常常用的東西,很多人使用組件都是通過一個一個文件去引用和註冊。如果一個組件在整個項目裏面的使用次數較多,每一次使用都需要引用並註冊,就會顯得特別麻煩
當們在項目需要重複多次使用該組件,會導致出現很多重複的引入和註冊代碼,既繁瑣又不雅觀。因此我們可以通過一個全局的Js文件來管理,將需要多次使用的組件進行全局註冊
創建全局.js文件管理全局組件
// 1 - globalComponent.js
import Vue from 'vue' // 引入vue
// 處理首字母大寫 abc => Abc
function changeStr(str){
return str.charAt(0).toUpperCase() + str.slice(1)
}
/*
require.context(arg1,arg2,arg3)
arg1 - 讀取文件的路徑
arg2 - 是否遍歷文件的子目錄
arg3 - 匹配文件的正則
關於這個Api的用法,建議小夥伴們去查閱一下,用途也比較廣泛
*/
const requireComponent = require.context('.', false, /\.vue$/)
console.log('requireComponent.keys():',requireComponent.keys()) // 打印
requireComponent.keys().forEach(fileName => {
const config = requireComponent(fileName)
console.log('config:',config) // 打印
const componentName = changeStr(
// ./child1.vue => child1
fileName.replace(/^\.\//, '').replace(/\.\w+$/, '')
)
// 動態註冊該目錄下的所有.vue文件
Vue.component(componentName, config.default || config)
})
// 2 - 將globalComponent.js引入main.js
import global from './components/globalComponent'
// 3 - 使用這類組件不再需要引入和註冊,直接標籤使用即可
<template>
<div>
<h1>I am HelloWorld</h1>
<Child1></Child1>
</div>
</template>
require.context是什麼===>詳情見文章require.context是什麼