1

I have an area where people can upload their own user-image. But if they do not, I would like to display a default one.

After some googling, I found I can do so by doing something like -

<img :src="creatorImage" @error="defaultAvatar">

But, I am not sure how to then created a method to pass the correct (default) image into it.

0

3 Answers 3

2

I did it with a computed property, like this:

<template>
  <img :src="creatorImage" @error="imageError = true"/>
</template>

<script>
...
data() {
  return {
      imageError: false,
      defaultImage: require("@/assets/imgs/default.jpg")
  };
},
computed: {
    creatorImage() {
        return this.imageError ? this.defaultImage : "creator-image.jpg";
    }
}
...
</script>
0

I would suggest creating a component for this, as it sounds like something that will be used on more places.

JsFiddle example

Component

 Vue.component('img-with-default', {     
  props: ['defaultImg'],
  data: function () {
    return {
      defaultAvatar: this.defaultImg || 'https://cdn0.iconfinder.com/data/icons/crime-protection-people/110/Ninja-128.png'
    }
  },
  computed:{
    userImage: function() {
      if(this.uploadedImg != null) {
        return this.uploadedImg;
      } else {
        return this.defaultAvatar;
      }
    }
  },
  template: '<img :src="userImage">'
})

And using the commponent would be

HTML

<div id="editor">
  <img-with-default></img-with-default>

  <img-with-default default-img="https://cdn3.iconfinder.com/data/icons/avatars-15/64/_Ninja-2-128.png" ></img-with-default>
</div>

JS

new Vue({
  el: '#editor'  
})

With this you have the default image.


If you want you can create a component that would display passed img src or the default one.

Component

Vue.component('img-with-default', {     
  props: ['imgSrc'],
  data: function () {
    return {
      imageSource: this.imgSrc || 'https://cdn0.iconfinder.com/data/icons/crime-protection-people/110/Ninja-128.png'
    }
  },
  template: '<img :src="imageSource">'
})

and to use it

HTML

<div id="editor">
  <img-with-default></img-with-default>

  <img-with-default img-src="https://cdn3.iconfinder.com/data/icons/avatars-15/64/_Ninja-2-128.png" ></img-with-default>
</div>
1
  • Sorry for the slow reply, getting into the busy time of year!! Your response was absolutely perfect, I didn;t use it exactly like you mentioned, but with the great info you gave, I was able to do something similar and work it out! Thanks!!
    – KJParker
    Commented Dec 1, 2018 at 12:58
0

All of the above are unneededly complicated. Here is the easiest way to do it:

<img :src="image||'default.png'" />

Not the answer you're looking for? Browse other questions tagged or ask your own question.