这是我的组件。它需要一个道具 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>
我这样使用它:
<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>
但是图片没有加载。
原文由 TSR 发布,翻译遵循 CC BY-SA 4.0 许可协议
有一个奇怪的 JS 错误会破坏正确的图像加载(sry,我忘了它是什么,但我不久前在 stackoverflow 上找到了解决方案)。
有用的是像这样分解图像请求:
所以你在道具中只有你的图像名称并在没有大括号的情况下加载它。现在您也不必担心正确的路径。 @ 将找到正确的文件夹。
如果有人可以更好地解释这个的技术细节或找到其他线程的解决方案,请随时扩展我的答案。
编辑: 解释的第一部分:Webpack 不能只使用一个变量作为路径,因为那样它可能必须遍历数千个文件。所以你必须将 @/assets/ 部分作为文本。在这里更好地解释: Vue.js dynamic image src with webpack require() not working
还找不到为什么大括号不起作用。