vue require.context全局注冊組件的具體實現(xiàn)
? 作用:一個 Webpack 提供的 API 方法,通過 require.context()
函數(shù)可以獲取一個上下文,通常用來簡化大量頻繁的引入組件操作。?
require.context() 接收三個參數(shù):
directory
:要查找的目錄路徑isFindSub?
:是否查找子目錄regExp
:要匹配的文件正則表達(dá)式
const req = require.context('./component',true,/\.vue$/)
過程:require.context() 執(zhí)行后會返回一個 req 對象,該 req 對象中存在有一個 keys() 方法成員,
keys() 文件路徑數(shù)組
? 作用:它會返回一個 require.context() 方法在指定目錄下查找到的所有文件路徑數(shù)組。
const req = require.context('./component',true,/\.vue$/) console.log(req.keys()) // ['./component/SvgIcon.vue','./component/Form/Login.vue','./component/Channel.vue'...] req.keys().forEach(item => { ... })
在拿到所有待注冊組件的文件路徑之后,便可以傳給 req
對象本身進(jìn)行一個 import
解構(gòu)導(dǎo)出操作。
一、定義2個組件
scr/components/ComponentsA/index.vue
<template> <div>A組件</div> </template> <script> export default { name: 'ComponentA' } </script>
scr/components/ComponentsB/BBB/BBBB/index.vue
<template> <div>B組件</div> </template> <script> export default { name: 'ComponentB' } </script>
二、局部使用這兩個組件
<template> <div id="app"> <ComponentA /> <ComponentB /> </div> </template> <script> import ComponentA from '@/components/ComponentA' import ComponentB from '@/components/ComponentB/BBB/BBBB' export default { components: { ComponentA, ComponentB } } </script>
三、全局注冊組件
如果這2個組件是基礎(chǔ)性的組件,項目中好多地方都要用到,可以注冊成全局組件
src/requireAllComponents.js
import Vue from 'vue' const componentsContext = require.context('@/components', true, /index.vue$/) // true表示遞歸查找 正則匹配index.vue文件 componentsContext.keys().forEach(item => { const componentConfig = componentsContext(item).default Vue.component(componentConfig.name, componentConfig) // 全局注冊組件 })
main.js
import './requireAllComponents'
此時,便不再需要在每個組件中都引入這種基礎(chǔ)組件了
到此這篇關(guān)于vue require.context全局注冊組件的文章就介紹到這了,更多相關(guān)vue require.context全局注冊組件內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
vue父元素點(diǎn)擊事件與子元素點(diǎn)擊事件沖突問題
這篇文章主要介紹了vue父元素點(diǎn)擊事件與子元素點(diǎn)擊事件沖突問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-01-01Vue使用Vue Elements實現(xiàn)文件預(yù)覽功能
在現(xiàn)代 web 開發(fā)中,用戶與系統(tǒng)的交互體驗越來越重要,而文件上傳和文件預(yù)覽是最常見的交互場景之一,本文將詳細(xì)介紹如何在 Vue 項目中使用 Vue Elements 來實現(xiàn)文件預(yù)覽的功能,包括基本使用方法、常見實例、性能優(yōu)化以及樣式自定義等內(nèi)容,需要的朋友可以參考下2025-01-01關(guān)于element?ui中的el-scrollbar橫向滾動問題
這篇文章主要介紹了關(guān)于element?ui中的el-scrollbar橫向滾動問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-08-08Vue3項目中優(yōu)雅實現(xiàn)微信授權(quán)登錄的方法
用戶在微信端中訪問第三方網(wǎng)頁,可以通過微信網(wǎng)頁授權(quán)機(jī)制獲取用戶的基本信息,進(jìn)而實現(xiàn)所需要的業(yè)務(wù)邏輯,這篇文章主要給大家介紹了關(guān)于Vue3項目中優(yōu)雅實現(xiàn)微信授權(quán)登錄的相關(guān)資料,需要的朋友可以參考下2021-09-09Vue如何動態(tài)修改el-table的某列數(shù)據(jù)
這篇文章主要介紹了Vue如何動態(tài)修改el-table的某列數(shù)據(jù),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-04-04vue-router實現(xiàn)組件間的跳轉(zhuǎn)(參數(shù)傳遞)
這篇文章主要為大家詳細(xì)介紹了vue-router實現(xiàn)組件間的跳轉(zhuǎn),參數(shù)傳遞方法,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-11-11Vue+ElementUI項目使用webpack輸出MPA的方法
這篇文章主要介紹了Vue+ElementUI項目使用webpack輸出MPA的方法,本文圖文并茂給大家介紹的非常詳細(xì),具有一定的參考借鑒價值,需要的朋友可以參考下2019-08-08