圖片加載失敗后如何顯示默認圖片

當圖片image1加載失敗后,要顯示默認圖片image2,可以使用img中的onerror屬性顯示

<template>
  <img width="300" src="/image1.jpg" onerror="this.src='/image2.jpg'" />
</template>

但是直接用上面的形式表達容易出現(xiàn)的問題有,當圖片為一個變量時,圖片會無法即時顯示,t其中this.scr容易被誤會為上下文的值,其實這個值指向于img
標簽
那么修改上述的代碼為

<template>
  <!-- :src為vue3.4的語法糖,等同于:src=src -->
  <img width="300" :src />
</template>

<script setup lang="ts">
import { ref} from 'vue'

const src = ref('')

function loadImage(src:string) {
  return new Promise<string>((resolve,reject) => {
    //判斷圖片是否可以訪問,創(chuàng)建一個對象
    const image = new Image()
    image.src = src
    image.onload = () => resolve(src)
    image.onerror = (err) => reject(err)
  })
}

loadImage('/image1.jpg').then((res)=>{
  console.log(res)
  //如果加載成功
  src.value = res
}).catch((err)=>{
  src.value = '/image2.jpg'
})

</script>
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容