Yasin Demirkaya
Yasin Demirkaya

Reputation: 261

Vuejs - How to set the default value of a prop to a predefined data?

The question is simple. I want to define a data as follows;

data() {
  return {
    logoURL: "some-link/some-picture.png"
  }
}

and I want to set it to a prop's default state like this:

props: {
  infoLogoURL: {
    type: String,
    default: this.logoURL,
  },
}

Apparently it doesn't work the way I want and I have this error:

Uncaught TypeError: Cannot read property 'logoURL' of undefined

How can I manage this? Here is an example of how I use my props:

<cardComp
  infoTitle = "Info Title" 
  infoText = "Info Text" 
  infoSubIcon = "Sub Icon Name" 
  infoSubIconColor = "css-color-class" 
  infoSubText = "Sub Text" 
  infoDescription = "Some Text Description" 
  infoIcon = "Icon Name" 
  infoIconColor = "icon-color-css"
  infoLogoURL = "some-link/some-picture.png"
/>

And here is another question... I want to display infoIcon when there is no infoLogoURL. So let's say the link of that specific .png file is not available in a moment of time, so in that case, I want to display the infoIcon. When the .png file is available, I should only display the infoLogoURL, not the infoIcon. How do I do that?

Upvotes: 4

Views: 2896

Answers (2)

Majed Badawi
Majed Badawi

Reputation: 28404

You can define a computed property that returns the value of the prop "info_logo_url" when set, and that of data "logoURL" when not.

Concerning the second part of the question, another computed property can be defined to return the prop "info_logo_url" when set, and that of the prop "info_icon" when not.

const cardcomponent = Vue.component('card-component', {
  template: '#card-component',
  data(){
    return { logoURL: "some-link/some-picture.png" }
  },
  props: {
    info_logo_url: { type: String },
    info_icon: { type: String }
  },
  computed: {
    myInfoLogo() { return this.info_logo_url || this.logoURL; },
    myInfoIcon() { return this.info_logo_url || this.info_icon; },
  }
});

new Vue({
  el: '#app',
  components: { cardcomponent },
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <div>
    <cardcomponent info_logo_url="info logo URL" info_icon="info icon"/>
  </div><hr>
  <div>
    <cardcomponent info_logo_url="info logo URL"/>
  </div><hr>
  <div>
    <cardcomponent info_icon="info icon"/>
  </div>
</div>

<template id="card-component">
  <div>
    <b>myInfoLogo</b>: {{myInfoLogo}} - <b>myInfoIcon</b>: {{myInfoIcon}}
  </div>
</template>

Upvotes: 1

Dan Knights
Dan Knights

Reputation: 8368

You can't set the default value of a prop from data.

One way around this is to use a computed property instead:

computed: {
  defaultLogoURL: function() {
    return this.infoLogoURL || this.logoURL
  }
}

Upvotes: 6

Related Questions