gpt4 book ai didi

javascript - Vue.js 2 : Vue cannot find files from/assets folder (v-for)

转载 作者:搜寻专家 更新时间:2023-10-30 22:19:04 24 4
gpt4 key购买 nike

我将 Vue-cli 3 与 Webpack 一起使用,我的文件夹结构如下所示:

/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 有一个公共(public)文件夹。如果您使用的是 Vue CLI,它应该已经为您创建了一个公用文件夹,您必须将所有 Assets 放在该文件夹中。在官方 Vue.js documentation. 中阅读更多相关信息

示例文件夹结构:

/api
/public
/public/assets
/public/favicon.ico
/public/index.html
/src
index.js
app.json

等...

在公开场合,您可以放置​​静态 Assets ,例如图像、字体、favicon、robots.txt、sitemap.xml 等。

然后链接到您将使用的这些静态 Assets :

在您的模板 HTML 中:

<img src="/assets/some-image.svg" alt="Example" />

或者在你的组件 JS 中:

array: [
{
iconUrl: '/assets/some-image-1.svg',
label: 'Some Label'
}
]

否则你必须使用 require 因为它是从 src 文件夹中提取的,正如其他人已经说过的那样。但是可能没有真正的理由将它们放在那里,因此建议使用 /public/ 文件夹。

关于javascript - Vue.js 2 : Vue cannot find files from/assets folder (v-for),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52082968/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com