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

Nuxt 3中如何传递动态图片URL?适配数组图片场景

Nuxt 3 动态传递图片URL实现方案

针对数组场景下动态传递图片URL的需求,以下是两种适配Nuxt 3的实现方式,对应不同的资源存放目录:

场景1:图片放在public目录(对应Nuxt 2的static目录)

Nuxt 3中public目录下的资源会被直接复制到构建产物中,可通过根路径直接访问,无需额外处理:

子组件(Childcomponent.vue)

<template>
  <NuxtLink>
    <img :src="`/media/${work.image}.png`" alt="" />
  </NuxtLink>
</template>

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

父组件

保持原有数组结构即可:

<template>
  <div>
    <CardsCaseCard v-for="work in works" :key="work.id" :work="work" />
  </div>
</template>

<script setup>
const works = [
  { id: 1, image: 'office-1' },
  { id: 2, image: 'office-2' },
  { id: 3, image: 'office-3' },
]
</script>

场景2:图片放在assets目录(需构建工具处理,如压缩、哈希命名)

若图片存放在assets目录下,需通过new URL()让构建工具识别资源路径:

子组件(Childcomponent.vue)

<template>
  <NuxtLink>
    <img :src="getImageUrl(work.image)" alt="" />
  </NuxtLink>
</template>

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

// 根据实际目录结构调整相对路径
const getImageUrl = (imageName) => {
  return new URL(`../assets/media/${imageName}.png`, import.meta.url).href
}
</script>

父组件

同样保持原有数组结构即可。

进阶:使用Nuxt Image模块优化图片

若需要图片懒加载、格式转换等优化,可使用Nuxt官方的@nuxt/image模块:

  1. 安装模块:
npm install @nuxt/image
  1. 在nuxt.config.ts中配置:
export default defineNuxtConfig({
  modules: ['@nuxt/image'],
})
  1. 子组件中替换为<NuxtImg>:
<template>
  <NuxtLink>
    <NuxtImg :src="`/media/${work.image}.png`" alt="" />
  </NuxtLink>
</template>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 19:22:44