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

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ù):一個要搜索的目錄,一個標記表示是否還搜索其子目錄, 以及一個匹配文件的正則表達式
require.context("@/views/pageComponents",true,/.vue$/)
// 創(chuàng)建出一個context,其中文件來自非pageComponents目錄, request以`.vue`文件結(jié)尾注意點
一個 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項目工程中,封裝了很多組件,讓后在需要用到的頁面需要一個一個引入,
使用方法
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項目中使用require.context引入組件的文章就介紹到這了,更多相關(guān)vue require.context引入內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
vue3在構(gòu)建時使用魔法糖語法時defineProps和defineEmits的注意事項小結(jié)
在 Vue 3.2+ 版本中,可以使用 <script setup> 替代傳統(tǒng)的 script標簽來編寫組件,它提供了更簡潔的語法來編寫 Composition API 代碼,這篇文章主要介紹了vue3在構(gòu)建時使用魔法糖語法時defineProps和defineEmits的注意事項小結(jié),需要的朋友可以參考下2024-04-04
vue頁面切換項目實現(xiàn)轉(zhuǎn)場動畫的方法
這篇文章主要介紹了vue頁面切換項目實現(xiàn)轉(zhuǎn)場動畫的方法,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習或者工作具有一定的參考學(xué)習價值,需要的朋友們下面隨著小編來一起學(xué)習學(xué)習吧2019-11-11
Vue封裝一個Tabbar組件?帶組件路由跳轉(zhuǎn)方式
這篇文章主要介紹了Vue封裝一個Tabbar組件?帶組件路由跳轉(zhuǎn)方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-04-04
Vue3中的ref為何要用.value進行值的調(diào)用呢
這篇文章主要介紹了Vue3中的ref為何要用.value進行值的調(diào)用,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-09-09

