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模块:
- 安装模块:
npm install @nuxt/image
- 在nuxt.config.ts中配置:
export default defineNuxtConfig({ modules: ['@nuxt/image'], })
- 子组件中替换为
<NuxtImg>:
<template> <NuxtLink> <NuxtImg :src="`/media/${work.image}.png`" alt="" /> </NuxtLink> </template>
内容的提问来源于stack exchange,提问作者sonnyd
相关产品推荐
相关产品推荐

