"重要" Vue3 批量注冊(cè)全局組件

大致步驟:

1,新建.js文件,使用require提供的函數(shù)context加載某一個(gè)目錄下所有的.vue后綴的文件。
2,然后context函數(shù)會(huì)返回一個(gè)導(dǎo)入函數(shù)的ctx,它有一個(gè)keys()方法獲取所有文件路徑。
3,通過文件路徑數(shù)組,遍歷數(shù)組,在使用ctx根據(jù)路徑導(dǎo)入組件對(duì)象
4,遍歷的同事進(jìn)行全局注冊(cè)即可。

//參數(shù):1. 在那個(gè)目錄找 2.是否加載子目錄 3.加載的文件名(正則匹配)
export default {
 install (app){
 //批量注冊(cè)全局組建
 //加載該目錄下所有.vue文件
 const ctx = require.context('./',false,/\.vue$/)
 ctx.keys().forEach(()=>{
 //item:組件的地址 ctx(item) 導(dǎo)入這個(gè)組件
    const component = ctx(item).default 
    app.component(component.name , component)
    })
}

這樣就能自動(dòng)在文件夾下面找到.vue組件,并且自動(dòng)注冊(cè)了。

案例

Loading.vue

<template>
  <div class="loading">
    <a-spin :tip="$t('common.loading')+'...'">
    </a-spin>
  </div>
</template>
<script>
export default {
  name: 'Loading'
}
</script>
  <!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="less" scoped>
.loading {
    padding-top:30px;
    text-align: center;

}
</style>

index.ts

// 參數(shù):1. 在那個(gè)目錄找 2.是否加載子目錄 3.加載的文件名(正則匹配)
export default {
  install(app) {
    // 批量注冊(cè)全局組建
    // 加載該目錄下所有.vue文件
    const ctx = require.context('./', false, /\.vue$/)
    ctx.keys().forEach((item) => {
      // item:組件的地址 ctx(item) 導(dǎo)入這個(gè)組件
      const component = ctx(item).default
      debugger
      app.component(component.name, component)
    })
  }
}

main.ts

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

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

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