TSR*_*TSR 11 vue.js vue-component
这是我的组件。它需要一个道具imageUrl,它String从 URL 引用图像或从资产文件夹引用本地资产
<template>
<div class="flex" style="height: 155px;align-items: center">
<div class="avatar" style="height: 130px;width: 130px">
<img :src="require(`imageUrl`)" height="130" width="130" style="border-radius: 50%"/>
</div>
<div class="flex flex-column" style="margin-left: 31px">
<div class="flex" style="font-weight: bold">
{{fullName}}
</div>
<div class="flex" style="">
{{title}}
</div>
<div style="height: 20px"></div>
<div class="flex" style="text-align: start">
{{content}}
</div>
</div>
</div>
</template>
<script>
export default {
name: "ReviewTile",
props: {
imageUrl: String,
fullName: String,
title: String,
content: String
}
}
</script>
<style scoped>
</style>
Run Code Online (Sandbox Code Playgroud)
我像这样使用它:
<ReviewTile
image-url="../assets/Eugene.png"
full-name="Eugene B.
"
title="UI/UX Designer."
content=" Christabel is one of the business world’s truly great deal makers and strategists, easily on par with
the best of the strategy consultants and designers I have worked with at SOS-HGIC and Kleio. She is also
a world-class human being."
></ReviewTile>
<div style="background-color: #b7b7b7;height: 1px; margin: 33px 0px"></div>
<ReviewTile
image-url="../assets/headshot_black1.png"
full-name="Gilliam D."
title="Web designer/Developer"
content="Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo."
></ReviewTile>
Run Code Online (Sandbox Code Playgroud)
但图像没有加载。
Sar*_*ive 20
有一个奇怪的 JS 错误会破坏正确的图像加载(对不起,我忘了它是什么,但我不久前在 stackoverflow 上找到了解决方案)。
像这样分解图像请求是有帮助的:
:src="require('@/assets/' + imageName + '')"
Run Code Online (Sandbox Code Playgroud)
因此,您在道具中只有您的图像名称,并在没有大括号的情况下加载它。现在您也不必担心正确的路径。@ 将找到正确的文件夹。
如果有人可以更好地解释这个的技术细节或找到解决方案的另一个线程,请随时扩展我的答案。
编辑:解释的第一部分:Webpack 不能仅使用变量作为路径,因为这样它就必须遍历潜在的数千个文件。所以你必须将@/assets/部分作为文本。在这里解释得更清楚:Vue.js dynamic image src with webpack require() not working
尚无法找到为什么大括号不起作用。
如果所有图像都位于同一文件夹中,则只需将文件名作为 props 传递即可:
<ReviewTile
image-url="Eugene.png"
...
></ReviewTile>
<ReviewTile
image-url="headshot_black1.png"
...
></ReviewTile>
Run Code Online (Sandbox Code Playgroud)
然后在ReviewTitle组件中,需要imageUrl资产路径:
<div class="avatar">
<img :src="require(`../assets/${imageUrl}`)" />
</div>
Run Code Online (Sandbox Code Playgroud)
注意:
如果所有图像具有相同的扩展名,您甚至可以在组件中.png编写文件名,如 和:image-url="Eugene"<img :src="require(`../assets/${imageUrl}.png`)" />
如果你在url中发送图片的路径,那么你可以直接使用props,
但请确保您提供了图像的正确路径。
<img :src="imageUrl" height="130" width="130" style="border-radius: 50%"/>
Run Code Online (Sandbox Code Playgroud)
还要更改其他组件中的道具名称
// Wrong
<ReviewTile
image-url="../assets/Eugene.png"
full-name="Eugene B.
// correct one would be something like this
<ReviewTile
:imageUrl="../assets/Eugene.png"
full-name="Eugene B.
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11933 次 |
| 最近记录: |