背景:
页面有多张图片,动态的设置图片的链接src, 即: :src
解决方法:
<template>
<div>
<img v-for="for group in groups" :src="exportImgSrc(group.url)">
</div>
</template>
<script setup lang="ts">
import { ref } from 'vue';
let groups = [
{"url": "zicky-home-ride11.jpg","tag":"LIFE","title":"SUNRISE","content":"It is a nice day", "location":"Beijing", "date": "2022/02/02"} ,
{"url": "home-reading.jpg","tag":"LIFE","title":"SUNRISE","content":"It is a nice day", "location":"Beijing", "date": "2022/02/02"},
{"url": "nlp-meeting.jpg","tag":"LIFE","title":"SUNRISE","content":"It is a nice day", "location":"Beijing", "date": "2022/02/02"},
{"url": "reader.jpg","tag":"LIFE","title":"SUNRISE","content":"It is a nice day", "location":"Beijing", "date": "2022/02/02"}
]
const exportImgSrc = (name: string): string => {
return new URL(`../../assets/moments/${name}`, import.meta.url).href;
};
</script>
此处, 一定要写为: ${name}。 此处如果图片地址为静态的(写死了地址),编译后,代码中的图片地址为静态的,编译后的图片地址带有hash, 导致找不到图片,前端就无法显示图片。
有关图片处理见说明:
https://vite-pwa-org.netlify.app/guide/static-assets