目录背景require.context 是什么?require.context 的基本用法require.content 的应用场景背景 我们在Vue项目中,我们可能或有很多的组件需
我们在Vue项目中,我们可能或有很多的组件需要全局注册,大家有没有遇到这样的烦恼,组件太多,需要一个一个引入注册呢?
require.context 是webpack的api,我们可以通过require.context()函数来创建自己的context。
语法如下
require.context(
directory,
(useSubdirectories = true),
(regExp = /^\.\/.*$/),
(mode = 'sync')
);
示例: require.context可以传三个参数:一个要搜索的目录,一个标记表示是否还搜索其子目录, 以及一个匹配文件的正则表达式
require.context("@/views/pageComponents",true,/.vue$/)
// 创建出一个context,其中文件来自非pageComponents目录, request以`.vue`文件结尾
注意点
一个 context module 会导出一个(require)函数,此函数可以接收一个参数:request。此导出函数有三个属性:resolve, keys, id。 返回的函数
WEBpackContext(req) {
var id = webpackContextResolve(req);
return __webpack_require__(id);
}
案例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>
到此这篇关于vue项目中使用require.context引入组件的文章就介绍到这了,更多相关vue require.context引入内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!
--结束END--
本文标题: vue项目中使用require.context引入组件
本文链接: https://www.lsjlt.com/news/171593.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-01-12
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0