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
相关产品推荐
相关产品推荐

