这是我的组件。需要 Prop imageUrl
这是 String
从 URL 引用图像或从 Assets 文件夹引用本地 Assets
<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>
但图像没有加载。
最佳答案
有一个奇怪的 JS 错误会破坏正确的图像加载(对不起,我忘了它是什么,但我不久前在 stackoverflow 上找到了解决方案)。
像这样分解图像请求是有帮助的:
:src="require('@/assets/' + imageName + '')"
因此,您在 Prop 中只有您的图像名称,并在没有大括号的情况下加载它。现在您也不必担心正确的路径。 @ 将找到正确的文件夹。
如果有人可以更好地解释这个的技术细节或找到解决方案的另一个线程,请随时扩展我的答案。
编辑:解释的第一部分:Webpack 不能仅使用变量作为路径,因为那样它可能必须遍历数千个文件。所以你必须拥有 @/assets/部分作为文本。这里解释得更清楚:Vue.js dynamic image src with webpack require() not working
尚无法找到为什么大括号不起作用。
关于vue.js - 如何将 imageUrl 作为 Prop 传递?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56083044/