While Vue makes it easy to add properties to your component, sometimes you need a little more control over what kinds of things are allowed into it. Thankfully, Vue provides built-in ways to add type checking, validation, default values, and constraints to your prop definitions.
You can easily add type checking to your property definitions by adding the type property to it.
For example, the following component constrains the possible input values to numbers.
<template>
<h2>Numerical Property {{imperfectNumber}}</p>
</template>
<script>
export default {
props: {
imperfectNumber: {
type: Number
}
}
}
</script>
<template>
<child-component :imperfectNumber="41"></child-component>
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
components: {
ChildComponent
}
}
</script>
Allowed type values are:
You can force a property to be required by adding the required: true value to the property definition.
props: {
imperfectNumber: {
type: Number,
required: true
}
}
Alternatively, you can set a default value for the property, which will be used if no value is passed in.
props: {
imperfectNumber: {
type: Number,
default: 43
}
}
You can even set it to a function to generate dynamic default values!
props: {
imperfectNumber: {
type: Number,
default: () => Math.random()
}
}
For more complex objects, you can also add custom validator functions. A validator is simply a function that takes the input property value and returns a boolean, true if it is valid, false otherwise.
props: {
imperfectNumber: {
type: Number,
validator: value => {
// Only accepts values that contain the string 'cookie-dough'.
return value.indexOf('cookie-dough') !== -1
}
}
}
By combining these properties you can robustly handle almost any values a user might throw at your component and make it considerably easier to use an understand. :D
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
This textbox defaults to using Markdown to format your answer.
You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!
Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.
Full documentation for every DigitalOcean product.
The Wave has everything you need to know about building a business, from raising funding to marketing your product.
Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.
New accounts only. By submitting your email you agree to our Privacy Policy
Scale up as you grow — whether you're running one virtual machine or ten thousand.
Sign up and get $200 in credit for your first 60 days with DigitalOcean.*
*This promotional offer applies to new accounts only.