Home > Back-end >  How to pass "conditional" default value by checking its value in the Vue component
How to pass "conditional" default value by checking its value in the Vue component

Time:10-23

Component

props: {
  image: {
    type: String,
    default() {
       return this.defaultImage
    }
  }
},

computed: {
  defaultImage() {
     return this.$config.baseUrl   '/images/default.jpg'
  }
},

Using the above component, when prop-image is not present, the component returns default-image successfully.

<image-uplaoder />

But I want to achieve, if I pass the value for prop-image and the value is null, it should still return default-image. Currently, it returns nothing.

<image-uplaoder :image="data.image" /> 

Tried (can't we do something like) as follows?

computed: {
  defaultImage(value) {
    if(!value || value === null) {
      return this.$config.baseUrl   '/images/default.jpg'
    }
  }
},

CodePudding user response:

Instead of the prop's default() option, the computed property should contain the logic to use a default value:

// ImageUploader.vue
export default {
  props: {
    image: String,
  },
  computed: {
    imgUrl() {
      return this.image || (this.$config.baseUrl   '/images/default.jpg')
    }
  }
}

Then bind the computed property to your <img>.src:

<img :src="imgUrl">

demo

  • Related