我在 Webpack 中使用 Vue-cli 3,我的文件夹结构如下所示:
/public
/src
/assets
p1.jpg
p2.jpg
App.vue
main.js
我在几个地方读到,为了让 Webpack 知道你的 /assets 在哪里,如果你在 Javascript 领域,你应该使用 require() 。
我确定此代码有效:
<template>
<div>
<ul>
<li v-for="photo in photos" :key="photo.id">
<img :src="photo.imageUrls.default" />
</li>
</ul>
</div>
</template>
<script>
/* For webpack to resolve URLs in javascript during the build, you need the require() function */
export default {
data() {
return {
photos: [
{
id: 1,
caption: 'P1',
series: '',
notes: '',
imageUrls: {
default: require('./assets/p1.jpg')
}
},
{
id: 2,
caption: 'P2',
series: '',
notes: '',
imageUrls: {
default: require('./assets/p2.jpg')
}
}
]
}
}
}
</script>
但是,这是行不通的。我在控制台中看到一个错误:“错误:找不到模块‘./assets/p1.jpg’”
<template>
<div>
<ul>
<li v-for="photo in photos" :key="photo.id">
<img :src="imagePath(photo)" />
</li>
</ul>
</div>
</template>
<script>
/* For webpack to resolve URLs in javascript during the build, you need the require() function */
export default {
data() {
return {
photos: [
{
id: 1,
caption: 'P1',
series: '',
notes: '',
imageUrls: {
default: './assets/p1.jpg'
}
},
{
id: 2,
caption: 'P2',
series: '',
notes: '',
imageUrls: {
default: './assets/p2.jpg'
}
}
]
}
},
methods: {
imagePath(photo) {
return require(photo.imageUrls.default);
}
}
}
</script>
有没有人可以帮助解释第二个例子中的错误?我希望避免将 require() 调用放入数据中,因为该数据可能来自服务器,而且在我看来将 require() 调用放入数据中似乎很奇怪。谢谢。
编辑:根据下面埃德加的建议,由于我的图像是服务器的一部分而不是应用程序,我可以将它们放入 /public 文件夹中的一个文件夹中,根本不处理 require() 。
原文由 Stephen 发布,翻译遵循 CC BY-SA 4.0 许可协议
Vue.js 有一个公共文件夹。如果您使用的是 Vue CLI,它应该已经为您创建了一个公用文件夹,您必须将所有资产放在该文件夹中。在官方 Vue.js 文档中阅读更多相关信息。
示例文件夹结构:
ETC…
在 public 中,您可以放置静态资产,例如图像、字体、favicon、robots.txt、sitemap.xml 等。
然后链接到您将使用的这些静态资产:
在您的模板 HTML 中:
或者在你的组件 JS 中:
否则你必须使用
require
因为它是从src
文件夹中提取的,正如其他人已经说过的那样。但是可能没有真正的理由将它们放在那里,因此建议使用/public/
文件夹。