vue項(xiàng)目中使用require.context引入組件
背景
我們在vue項(xiàng)目中,我們可能或有很多的組件需要全局注冊,大家有沒有遇到這樣的煩惱,組件太多,需要一個一個引入注冊呢?

require.context 是什么?
require.context 是webpack的api,我們可以通過require.context()函數(shù)來創(chuàng)建自己的context。
require.context 的基本用法
語法如下
require.context( directory, (useSubdirectories = true), (regExp = /^\.\/.*$/), (mode = 'sync') );
示例: require.context可以傳三個參數(shù):一個要搜索的目錄,一個標(biāo)記表示是否還搜索其子目錄, 以及一個匹配文件的正則表達(dá)式
require.context("@/views/pageComponents",true,/.vue$/)
// 創(chuàng)建出一個context,其中文件來自非pageComponents目錄, request以`.vue`文件結(jié)尾注意點(diǎn)
一個 context module 會導(dǎo)出一個(require)函數(shù),此函數(shù)可以接收一個參數(shù):request。此導(dǎo)出函數(shù)有三個屬性:resolve, keys, id。 返回的函數(shù)
webpackContext(req) {
var id = webpackContextResolve(req);
return __webpack_require__(id);
}require.content 的應(yīng)用場景
案例1
我們在vue項(xiàng)目工程中,封裝了很多組件,讓后在需要用到的頁面需要一個一個引入,
使用方法
const pageComponents = require.context("@/views/pageComponents",true,/.vue$/)
export const components={}
pageComponents.keys().forEach(item=>{
const name = path.basename(item,".vue")
components[name] = pageComponents(item).default
})案例2
加載所有的圖片
<div id="app">
<img src="@/assets/logo.png">
<li v-for="item in images">
<h3>Image: {{ item }}</h3>
<img :src="imgUrl(item)">
</li>
</div>
</template>
<script>
var imagesContext = require.context('@/assets/kittens/', false, /\.jpg$/);
console.log(imagesContext)
console.log(imagesContext('./kitten1.jpg'))
console.log(imagesContext.keys())
export default {
created: function() {
this.images = imagesContext.keys();
},
name: 'haha',
data() {
return {
images: [],
msg: 'Welcome to Your Vue.js App'
}
},
methods: {
imgUrl: function(path) {
//console.log('Path:' + path);
return imagesContext(path)
}
}
}
</script>
<style>
#app {
font-family: 'Avenir', Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
h1,
h2 {
font-weight: normal;
}
ul {
list-style-type: none;
padding: 0;
}
li {
display: inline-block;
margin: 0 10px;
}
a {
color: #42b983;
}
</style>到此這篇關(guān)于vue項(xiàng)目中使用require.context引入組件的文章就介紹到這了,更多相關(guān)vue require.context引入內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
vue3+echarts實(shí)現(xiàn)好看的圓角環(huán)形圖
這篇文章主要介紹了vue3+echarts實(shí)現(xiàn)好看的圓角環(huán)形圖效果,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-10-10
vue3插槽:el-table表頭插入tooltip及更換表格背景色方式
這篇文章主要介紹了vue3插槽:el-table表頭插入tooltip及更換表格背景色方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-06-06
element-plus一個vue3.xUI框架(element-ui的3.x 版初體驗(yàn))
這篇文章主要介紹了element-plus一個vue3.xUI框架(element-ui的3.x 版初體驗(yàn)),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-12-12
使用element組件table表格實(shí)現(xiàn)某條件下復(fù)選框無法勾選
這篇文章主要介紹了使用element組件table表格實(shí)現(xiàn)某條件下復(fù)選框無法勾選問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-03-03

