javascript - Vue.js 2:Vue 无法从 /assets 文件夹中找到文件 (v-for)
问题描述
我正在使用带有 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() 调用对我来说似乎很奇怪。谢谢。
编辑:根据 Edgar 在下面的建议,由于我的图像是服务器的一部分而不是应用程序的一部分,我可以将它们放入 /public 文件夹中的文件夹中,根本不处理 require() 。
解决方案
Vue.js 有一个公用文件夹。如果您使用的是 Vue CLI,它应该已经为您创建了一个公用文件夹,您必须将所有资产放在此文件夹中。在官方Vue.js 文档中了解更多信息。
示例文件夹结构:
/api
/public
/public/assets
/public/favicon.ico
/public/index.html
/src
index.js
app.json
ETC...
在公共场合,您可以放置静态资产,例如图像、字体、favicon、robots.txt、sitemap.xml 等。
然后链接到您将使用的这些静态资产:
在您的模板 HTML 中:
<img src="/assets/some-image.svg" alt="Example" />
或者在你的组件 JS 中:
array: [
{
iconUrl: '/assets/some-image-1.svg',
label: 'Some Label'
}
]
否则,您必须使用require
它,因为它是从src
文件夹中拉出的,正如其他人已经说过的那样。但是可能没有真正的理由将它们放在那里,因此/public/
建议使用文件夹。
推荐阅读
- java - 如何将捕获的图像保存到图库?
- docker-swarm - Docker Windows 主节点“docker swarm init”导致同一虚拟网络中的工作节点不再看到主节点
- loops - 我正在与一个班级一起改变声音的音高,但我无法让声音循环播放
- mysql - 在mysql查询中,当转换十进制值时,它显示不同的值
- android-studio - Android Studio 中弹出“无法找到 adb”
- python - 查找非 nan 值之间的上一个时间间隔和下一个时间间隔
- javascript - 有没有办法将裁剪的图像转换为 JavaScript 中的文件对象?
- powershell - 如何使用 powershell 启动teams.exe
- docker - docker:指定 Dockerfile - “docker build” 需要 1 个参数
- visual-studio-code - 我无法在 VSC 中复制或剪切任何东西