Vue 里面,加载本地图片,:src=””直接写成变量是不行的 …
演示网址:https://vue.cctv3.net/#/dynamicPathAsSrc
封装DynamicPathImage.vue
:
<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); 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>
|