How To Show Default Image On Error In Vue.js

In this article, we will learn how to show default image on error in vue,js

Step 1: Create a new project:

vue create default-error-image-demo

Step 2: Open App.vue file and add the following in it:

<template>
  <div id="app">
    <img :src="image" @error="imageErrors = true" />
  </div>
</template>
<script>
export default {
  name: 'App',
  data() {
    return {
      imageErrors: false,
      defaultImage: require('@/assets/logo.png'), // Add default image path
      actualImage: require('@/assets/flower.jpg'),
    };
  },
  computed: {
    image() {
      return this.imageErrors ? this.defaultImage :this.actualImage; // Add the actual image path 
    }
  },
};
</script>
<style>
#app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

Code in Action:

how-to-show-default-image-on-error-in-vue

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories