vite2 + vue3.0 + js 自動注冊加載全局公共組件

vite2不能使用webpack的require.context()方式讀取文件
vite2有自己的方法:
1、import.meta.glob()
2、import.meta.globEager()

在src/components 文件夾下創(chuàng)建index.js文件

 // index.js文件
 // 公共組件規(guī)范:
 //   1、在src/components目錄下創(chuàng)建目錄,目錄結(jié)構(gòu)為一級,即 src/components/組件目錄/xxx.vue
 //   2、目錄名稱必須與組件使用時的名稱一致, 即目錄名就是組件名
 //   例:有一個公共組件 <submit-confirm />那么在創(chuàng)建目錄時,目錄的名稱必須為SubmitConfirm
 //   src
 //      components
 //          SubmitConfirm
 //              index.vue // vue文件的名稱可以隨便定義

import { defineAsyncComponent } from 'vue'

// 獲取src/components文件夾下所有vue文件,可以根據(jù)項目需求,
// 在components下創(chuàng)建一個global文件夾專門放置所有的公共組件
// const components = import.meta.glob('./global/*/*.vue')
const components = import.meta.glob('./*/*.vue')
export default function install (app) {
  for (const [key, value] of Object.entries(components)) {
    // 因為我設(shè)計的是組件名稱就是目錄名稱,所以這里這樣取,也可以根據(jù)vue的文件名稱,看個人喜好
    const name = key.split('/')[1] 
    // 這里的main是我的layout,不需要注冊為公共組件
    if (name !== 'main') {
      app.component(name, defineAsyncComponent(value))
    }
  }
}

在main.js文件中import并use

// main.js
import { createApp } from 'vue'
import App from './App.vue'
import components from './components/index.js'

createApp(App).use(components).mount('#app')

在項目的其它位置就可以直接使用創(chuàng)建的公共組件了 如上面SubmitConfirm組件

// src/views/home.vue
<template>
  <submit-confirm />
</template>

宿醉好難受,可能寫的不是很明白,但是上面代碼直接用沒問題。希望可以幫到需要的人

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

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