Declaring props with Vue.js can include more than just the definition of the data passed from the parent to the child component. Let’s see how a more complex validation is declared.
defineProps({type:{// first you define your validation rule,
// below, the `validValues` are represented by a string array.
// see https://vuejs.org/guide/components/props.html#prop-validation
validator(value){constvalidValues=["primary","ghost","dashed","link","text","default",];// if the value provided exists in the array of valid values,
// then the prop is accepted.
returnvalidValues.includes(value);},// omit the following if the prop is required with no default value.
default(){return"default";},},});
With TypeScript, it’d look like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
import{PropType}from"vue";defineProps({type:{// PropType is used to annotate a prop with more
// advanced types when using runtime props declarations.
type:StringasPropType<"primary"|"ghost"|"dashed"|"link"|"text"|"default">,default:"default",validator:(prop: string)=>["primary","ghost","dashed","link","text","default"].includes(prop),},});