• By Jake Dohm
Vue Prop Defaults and Validators
Code
Here’s the code for the finished prop definition, including a default and validator.
export default {
props: {
color: {
type: String,
default: 'teal',
validator: function(value) {
if (value === 'teal' || value === 'orange') {
return true
} else {
return false
}
},
},
},
}
Bonus tip
Another 🔥 tip for you: I find myself usually writing validators for string props, so one way to simplify the validator is to create an array of allowed values and use the “includes” array method to check if the passed in value matches an allowed value. Here’s how that would look for this example:
export default {
props: {
color: {
type: String,
default: 'teal',
validator: function(value) {
const validColors = ['teal', 'orange']
return validColors.includes(value)
},
},
},
}