[Vuejs]-Vue fallback to asset images

6๐Ÿ‘

โœ…

Iโ€™d use v-if/v-else to show the appropriate image based on whether entity.url exists ..

<img v-if="entity.url" :src="entity.url" />
<img v-else src="@/assets/images/default.png" />
๐Ÿ‘คHusam Ibrahim

1๐Ÿ‘

In Vue 3, you can put an @error event on the image, so if the URL returns a 404, you can execute arbitrary logic:

<script setup>
import { ref } from 'vue';

const isProfileImageBroken = ref(false);

const handleBrokenImage = () => {
    console.log('image broke');
    isProfileImageBroken.value = true;
};
</script>

<template>
    <i v-if="!auth.user.image || isProfileImageBroken" class="icon-user icon-lg"></i>
    <img
        v-if="auth.user.image && !isProfileImageBroken"
        :src="auth.user.image"
        class="w-6 h-6 rounded-full object-cover"
        @error="handleBrokenImage"
    >
</template>
๐Ÿ‘คagm1984

0๐Ÿ‘

new Vue({
  el: '#app',
  data: {
    message: 'Hello Vue.js!',
    imageData:{ imgUrl:'https://upload.wikimedia.org/wikipedia/commons/thumb/f/f9/Wiktionary_small.svg/350px-Wiktionary_small.svg.png',
    
    }
  },
  methods: {
  	getUrlData(data) {
    	if (data && data.imgUrl) {
      	return data.imgUrl
      }
      else {
      	return "@/assets/images/default.png"
      }
    }
  }
})
<div id="app">
  <p>{{ message }}</p>
  <img :src="getUrlData(imageData)">
</div>

Try this should work in your case! and let me know if you are getting any errors

๐Ÿ‘คRAHIL KHAN

Leave a comment