文章內(nèi)重點(diǎn)在于 require.context 的使用 具體可查看 webpack官網(wǎng)
vue-cli 工程建的項(xiàng)目 components/index.js
/**
* 創(chuàng)建一個(gè)引入文件上下文
* 不懂上下文的 參考語文對(duì)于上下文的理解 及 context 的英語翻譯
* require.context 的參數(shù)說明可查看 webpack 文檔 或百度 高頻組件引入
*/
const componentsContext = require.context("./", false, /\.vue/);
const install = app => { // Vue 編寫插件 如需了解 可前往 vue 官網(wǎng)
componentsContext.keys().forEach( path => { // keys 函數(shù)拿到目錄下符合正則規(guī)則的所有文件 返回一個(gè)路徑數(shù)組
const componentName = path.split('/')[1].replace('.vue' , ''); // 將文件名截取下來作為組件名
const component = componentsContext(path); // 創(chuàng)建組件 context
app.component(componentName , component); // 全局注冊(cè)組件 (不推薦大量全局注冊(cè)組件,此套方法同樣可用于 其它文件的引入 css js. etc)
})
}
export default { // 到處 install 函數(shù) install 命名是關(guān)鍵 (如需了解 : you can go to Vue Official Website)
install,
}
- main.js (使用Vue3)
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import frequentlyComponents from './components'
const app = createApp(App); // vue3 變動(dòng)通過 createApp 函數(shù)生成 Vue 實(shí)例
app.use(frequentlyComponents); // 將插件 | 組件添加到 Vue 實(shí)例
app.use(store).use(router).mount('#app')
- 到此 就可以在 .vue 文件內(nèi) 直接使用全局引入的組件 無需 import 導(dǎo)入