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

NuxtJS中图片路径undefined报404如何设置默认图片解决

NuxtJS图片不存在时加载默认图实现方案

问题原因

404报错的核心原因是front.featured_image字段值为undefined时,JS字符串拼接会直接将undefined作为字符串拼入路径,最终请求http://localhost/storage/xxx/undefined这类无效地址。

实现方式

可根据自身代码场景选择以下任意一种方案:

  • 模板内直接兜底(改动最小)
    不需要修改原有computed/methods逻辑,直接在绑定src属性时做字段判断,不存在就返回本地默认图路径(默认图建议放在Nuxt的static目录下,直接写根路径即可访问):

    <img 
      :src="front.featured_image ? featuredImage + front.featured_image : '/default-image.png'" 
      :alt="front.title" 
    />
    
  • 逻辑封装到计算属性(单条数据场景适用)
    如果当前页面只处理单条front数据,可以直接把完整路径拼接、兜底逻辑都放到computed里,模板代码更简洁:

    computed: {
      fullFeaturedImage() {
        const basePath = this.$config.myPublicVariable + 'storage/'
        return this.front.featured_image ? basePath + this.front.featured_image : '/default-image.png'
      }
    }
    

    模板直接绑定计算属性即可:

    <img :src="fullFeaturedImage" :alt="front.title" />
    
  • 逻辑封装到方法(列表渲染场景适用)
    如果是用v-for渲染多条front数据,用传参的方法更灵活,可替换原有featuredImage方法:

    methods: {
      getFeaturedImage(imgPath) {
        const basePath = this.$config.myPublicVariable + 'storage/'
        return imgPath ? basePath + imgPath : '/default-image.png'
      }
    }
    

    模板调用时传入当前项的图片字段:

    <div v-for="front in frontList" :key="front.id">
      <img :src="getFeaturedImage(front.featured_image)" :alt="front.title" />
    </div>
    

额外容错优化

如果需要兼容「字段存在但服务器端图片资源已失效」的场景,可以给img标签加error事件做二次兜底,避免出现裂图:

<img 
  :src="getFeaturedImage(front.featured_image)" 
  :alt="front.title"
  @error="e => e.target.src = '/default-image.png'"
/>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 22:54:21