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

发布于:2024-10-15 ⋅ 阅读:(128) ⋅ 点赞:(0)

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>


网站公告

今日签到

点亮在社区的每一天
去签到