You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Nuxt 3中如何为img src设置动态变量?

解决Vue动态设置img src无效的问题

核心原因

webpack编译静态资源时,需要明确的路径规则才能正确解析资源。直接拼接~assets/...这类字符串无法被webpack识别,而动态require全变量路径时,webpack无法提前预知要打包的资源范围,导致报错。

可行解决方案

方案1:父组件提前解析资源路径再传递

在父组件的about数据中,先用require处理图片路径,再传递给子组件:

<!-- 父组件 -->
<template>
  <ChildComponent v-for="item in aboutList" :key="item.id" :about="item" />
</template>

<script setup>
const aboutList = [
  {
    id: 1,
    img: require('@/assets/images/image.png'), // 提前完成路径解析
    // 其他字段...
  },
  // 更多列表项...
];
</script>

子组件直接使用传递过来的解析后路径:

<!-- 子组件 -->
<template>
  <img :src="about.img" alt="card image" />
</template>

<script setup>
const props = defineProps({
  about: {
    type: Object,
    required: true,
  },
});
</script>

方案2:子组件基于固定基础路径动态拼接

如果父组件只能传递图片文件名(如image.png),子组件用固定基础路径+动态文件名的方式require:

<!-- 子组件 -->
<template>
  <img :src="cardImg" alt="card image" />
</template>

<script setup>
const props = defineProps({
  about: {
    type: Object,
    required: true,
  },
});

// 固定基础路径,仅动态替换文件名
const cardImg = require(`@/assets/images/${props.about.img}`);
</script>

注意事项

  • 不要用~作为路径前缀,Vue项目默认@是src目录的别名,webpack能直接识别解析。
  • 动态require必须保留固定的基础路径部分,不能让整个路径都是变量,否则webpack无法提前扫描并打包对应资源。

内容的提问来源于stack exchange,提问作者Moemen Hussein

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 04:45:58