Vue动态加载本地的图片资源

Snipaste 2024 12 02 21 16 36

Vue 里面,加载本地图片,:src=””直接写成变量是不行的 …

演示网址:https://vue.cctv3.net/#/dynamicPathAsSrc

封装DynamicPathImage.vue

<!-- 动态路径的public/图片 -->
<template>
<div :style="props.style" @click="emits('click')">
<img v-if="imageSrc" :style="props.style" :src="imageSrc" alt="" />
</div>
</template>

<script setup lang="ts">
import { onMounted } from "vue";
import { watch } from "vue";
import { ref } from "vue";

const imageSrc = ref("");
const props = defineProps(["style", "src"]);
const emits = defineEmits(["click"]);

const loadSrc = async (url: string) => {
const response = await fetch(url); // 确保路径相对 `public/`
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const blob = await response.blob();
imageSrc.value = URL.createObjectURL(blob);
};

watch(
() => props.src,
(s) => {
loadSrc(s);
}
);

onMounted(() => {
loadSrc(props.src);
});
</script>
<DynamicPathImage :src="src" style="width: 198px" @click="() => {}" />

测试:

<script setup lang="ts">
import { ref } from "vue";
import DynamicPathImage from "./components/dynamicPathImage.vue";
const src = ref("");
</script>

<template>
<div class="dynamic-path-as-src">
<n-flex vertical :align="'center'">
<DynamicPathImage :src="src" style="width: 198px" @click="() => {}" />
<div>Path: {{ src }}</div>
<n-flex>
<n-space
><n-button
v-for="(item, index) in [1, 2, 3]"
:key="index"
@click="src = `/images/Alipay0${item}.jpg`"
>第{{ index + 1 }}张图片</n-button
></n-space
>
</n-flex>
</n-flex>
</div>
</template>

<style>
.dynamic-path-as-src {
min-height: 100vh;
display: flex;
flex-direction: column;
justify-content: center;
display: flex;
.mobile {
}
}
</style>
作者

陈桥驿站

发布于

2024-12-02

更新于

2025-01-15

许可协议

评论