Configuring property values

We can further configure our property values by instead setting them as an object. This allows us to define things such as defaults, types, validators, and so on. Let's do this with our buttonText property:

export default {
props: {
buttonText: {
type: String,
default: "Fancy Button!",
required: true,
validator: value => value.length > 3
}
},
}

Firstly, we're ensuring that we can only pass String types into this property. We can also check against other types, such as:

According to web component good practices, sending primitive values to props is a good practice.

Under the hood, this is running the instanceof operator against the property so it could also run a check against constructor types, as seen in the following screenshot:

At the same time, we can also check for multiple types using the array syntax:

export default {
props: {
buttonText: {
type: [String, Number, Cat],
}
},
}

Next, we're setting the default text to be FancyButton!, which means that by default, if this property wasn't set, it'd have that value. We've also set required equal to true, meaning that any time we create a FancyButton we have to include the buttonText property.

This is currently a contradiction in terms (that is, default value and required), but there are times where you'd want a default value where the property isn't required. Finally, we're adding a validation function to this to specify that any time we set this property, it has to have a string length greater than three.

How do we know whether a property validation has failed? In development mode, we can check our development console and we should have a corresponding error. For example, if we forget to add the buttonText property on our component: