Use default if prop is null

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 retrieve some user data from my API and does not contain an avatar url. In this case, I want this component to use the default value, but it only works on transmission undefined, but is undefinednot valid in JSON, so I cannot return this from the API response.

Is there a way to implement what I want by going to nullor is there a better way to handle this?

+4
source share
3 answers

I would make a computed property based on the value of srcprop, which will return the default value if srcequal 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>
+3

:

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

, prop .

, , , prop.

0

Depending on the code that retrieves the data, you can deletekey from the parent to the URL. The component will receive undefinedand use the default value.

new Vue({
  el: '#app',
  data: {
    fetched: {
      src: '//via.placeholder.com/300x300?text=custom%20image'
    }
  },
  components: {
    avatar: {
      template: '#avatar-template',
      props: {
        src: {
          type: String,
          default: '//via.placeholder.com/350x150?text=default%20image'
        }
      }
    }
  },
  mounted() {
    // When you delete src, it uses the default
    setTimeout(() => Vue.delete(this.fetched, 'src'), 1000);
  }
});
<script src="//cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.min.js"></script>
<template id="avatar-template">
  <div>
    <img :src="src">
  </div>
</template>

<div id="app">
  <avatar :src="fetched.src"></avatar>
</div>
Run code
0
source

Source: https://habr.com/ru/post/1692004/


All Articles