Properties

Learn how to define and validate properties in your template.

Properties allow you to pass JavaScript values into components. Think of them as custom attributes that are accessible on a component.

Define props

To declare props, use the Component.defineProps function. Store the value in an exported props constant variable. For simple props, where you don’t want to validate the values, pass in an array of prop names.

<script>
export const props = Component.defineProps(['prop-1', 'prop-2', 'prop-3'])
</script>

Props must start with an alphanumeric character.

Validate props

Consider the data your props should accept. Usually, you’ll want to specify what data type a prop accepts. For example, if you create a prop called name, it should probably accept a string. If you take in a prop called age, it should probably take a number. But what happens when there's no value? Do you throw an error? Do you supply a default value?

Instead of simply declaring, “we take a prop called name and age," you can explicitly define validation and default values by passing in an object.

We can use the Component.props variable to define details around what each prop does. View the zod documentation for all the different validations you can apply.

export const props = Component.defineProps({
'prop-1': Component.props.string().default("default value"),
'prop-2': Component.props.boolean(),
'prop-3': Component.props.string().array().optional(),
'variant': {
schema: Component.props.string(),
label: 'Variant',
}
})

Each key is the name of a property like prop-1. Each value is either a PropType or ExtendedPropType.

  • PropType is an alias of ZodType from the zod validation library, which is what powers the validation underneath the hood.
  • ExtendedPropType is an object that accepts a PropType in the schema key, as well as any other, set keys. Examples that may be set are label, description, inputDisplay, and helpText when generating a UI for editing a component instance.
type ExtendedPropType = {
schema: PropType,
[key:string]?: any
}

Insert props

To pass in props, simply add attributes. By default, the value is treated as a string.

<my-component prop-1="string value here" />

To pass in a JavaScript value, use the #set: directive.

<my-component :prop-1="new Date()" />