我使用 Vue Js 创建了一个 Img 组件。并且该组件被传递到位于同一目录中的头文件,Img组件包含一个父div。当我将 Img 组件传递到头文件时,父 div 显示,但内部 img 未显示。即使 img 的路径是正确的,并且 img 在资产文件夹中也可用,当我直接添加 img 而不显示 img 组件时。
<template>
<div class="icon d-flex justify-content-center align-items-center ">
<img v-for="image in images" :key="image.src" :src="image.src" :alt="image.alt" class="icon_class" />
</div>
</template>
<script>
export default {
name: 'IconComponent',
props: {
images: {
type: Array,
required: true,
default: () => [],
},
},
};
</script>
<style scoped>
.icon {
width: 40px;
height: 40px;
background-color: #F0F2F6;
border-radius: 100px;
}
.icon_class {
height: 24px;
width: 24px;
}
</style><template>
<div class="icon d-flex justify-content-center align-items-center ">
<img v-for="image in images" :key="image.src" :src="image.src" :alt="image.alt" class="icon_class" />
</div>
</template>
<script>
export default {
name: 'IconComponent',
props: {
images: {
type: Array,
required: true,
default: () => [],
},
},
};
</script>
<style scoped>
.icon {
width: 40px;
height: 40px;
background-color: #F0F2F6;
border-radius: 100px;
}
.icon_class {
height: 24px;
width: 24px;
}
</style>
<template>
<div class="header_Parent d-flex justify-content-between">
<div class="logo">
<img src="@/assets/icons/header/logo.svg" alt="logo Icon">
</div>
<div class="icons_Block d-flex">
<IconComponent :images="imageUrls" altText="Logo Icon" />
</div>
</div>
</template>
<script>
import IconComponent from '@/components/layout/iconComponent.vue'
export default {
name: 'HeaderComponent',
components: {
IconComponent
},
data() {
return {
imageUrls: [
{ src: '@/assets/icons/header/icon1.svg' },
],
};
},
};
</script>
<style scoped>
.header_Parent {
padding: 8px 32px;
}
</style>[and this is snippet of img which is not showing](https://i.stack.imgur.com/psAdr.jpg)
我看到你正在使用 vite,这意味着当你传递这样的图像时,你必须使用 URL 构造函数。
所以在你的
IconComponent
中你需要有一个看起来像这样的方法:
getImageUrl(image) {
// or `/src/assets/${path}` if the path is always different
return new URL(`/src/assets/icons/${icon}`, import.meta.url)
}
然后在模板中使用它:
<div class="icon d-flex justify-content-center align-items-center ">
<img v-for="image in images" :key="image.src" :src="getImageUrl(image.src)" :alt="image.alt" class="icon_class" />
</div>
如果您愿意,您可以在这里阅读更多内容。