30

I have this simplified avatar component:

<template>
  <img :src="src">
</template>

<script>
export default {
  name: 'Avatar',
  props: {
    src: {
      type: String,
      default: '/static/avatar-default.png'
    }
  }
}
</script>

Let's say I fetch some user data from my API and it contains no avatar URL. In such case I want this component to use the default value but it only seems to work when passing undefined to it, but undefined is not valid in JSON so I cannot return that from the API response.

Is there a way to realize what I want by passing in null or is there a better way to handle this?

Kid Diamond
  • 2,232
  • 8
  • 37
  • 79
  • Does this answer your question? [Default values for Vue component props & how to check if a user did not set the prop?](https://stackoverflow.com/questions/40365741/default-values-for-vue-component-props-how-to-check-if-a-user-did-not-set-the) – T.Todua Nov 13 '20 at 20:54

3 Answers3

28

I would make a computed property based on the src prop value that will return a default value if the src is null:

<template>
  <img :src="source">
</template>

<script>
export default {
  name: 'Avatar',
  props: {
    src: { type: String }
  },
  computed: {
    source() {
      return this.src || '/static/avatar-default.png';
    }
  }
}
</script>
thanksd
  • 54,176
  • 22
  • 157
  • 150
8

You could also explicitly pass undefined as prop if src is null and you'd rather want the component to handle default values.

<template>
   <img :src="src || undefined">
</template>
nomadoda
  • 4,561
  • 3
  • 30
  • 45
3

This should do the trick:

<template>
  <img :src="src || '/static/avatar-default.png'">
</template>

And personally, I would keep the default value for the prop in addition to coercing null values to the default value.

As far as I know, you cannot achieve what you want through the prop definition.

kmc059000
  • 2,937
  • 1
  • 23
  • 27