自学内容网 自学内容网

img标签 :src 动态绑定图片地址,但是加载图片不成功

Vue CLI

在使用 Vue CLI 构建的应用程序中,Vue CLI 默认使用 Webpack 作为构建工具,Webpack 支持 require 语法来引入静态资源(如图片)。【Vue】】img使用 :src 动态绑定图片地址,但是加载图片不成功_vue动态绑定src图片出不来-CSDN博客

Vite

然而,Vite 使用了不同的构建策略,并且默认情况下不支持 require 语法来导入静态资源。

1.使用 Vite 的 import() 语法来动态导入静态资源。

这需要在组件中异步加载每个图片,并将路径存储在一个响应式变量中。

<template>
  <div>
    <u-image v-for="(item, index) in showSampleImage" :key="index" :src="item.src" :width="item.width" :height="item.height" />
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';

const showSampleImage = ref([
  {
    width: "311",
    height: "148",
    src: ""
  },
  {
    width: "311",
    height: "148",
    src: ""
  }
]);

onMounted(async () => {
  showSampleImage.value[0].src = (await import('../sampleImage/1.jpg')).default;
  showSampleImage.value[1].src = (await import('../sampleImage/2.jpg')).default;
});
</script>

2使用 import.meta.glob 批量导入

<template>
  <div>
    <u-image v-for="(item, index) in showSampleImage" :key="index" :src="item.src" :width="item.width" :height="item.height" />
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import images from '../sampleImage/*.jpg';

const showSampleImage = ref([
  {
    width: "311",
    height: "148",
    src: ""
  },
  {
    width: "311",
    height: "148",
    src: ""
  }
]);

onMounted(() => {
  Object.keys(images).forEach((path, index) => {
    images[path]().then(module => {
      showSampleImage.value[index].src = module.default;
    });
  });
});
</script>


原文地址:https://blog.csdn.net/weixin_66549669/article/details/142873043

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!