LeBlaireau
LeBlaireau

Reputation: 17467

Vuejs - pass through prop if it exists or zero

I have a component

<score :totalScore="totalScore || 0"> </scrore>

The score is usually set to an int but there are times when the score does not have any value. In these cases how can I pass though 0 to catch this error?

Upvotes: 0

Views: 334

Answers (1)

Andy
Andy

Reputation: 3012

In your "score" component, define the prop like this:

Vue.component('score', {
//...
props: {
    totalScore: {
        type: Number,
        default: 0
    }
},
//...
// optionally you could also define a computed property to set 0 by default
computed: {
    totalScoreInt(){
        return parseInt(this.totalScore) || 0;
    }
}    
//...
});

then use it like this:

<score :total-score="totalScore"> </scrore>

Also, in templates you should not define props in camelCase, you should use kebab-case instead as html attributes are case-insensitive and any uppercase characters are interpreted lowercase.

see the docs: https://v2.vuejs.org/v2/guide/components-props.html#Prop-Validation

fiddle: https://jsfiddle.net/thogrtyr/

Upvotes: 2

Related Questions