Vue 3 Props Definition and Validation Rules

Here is an example demonstrating how to use the props option in Vue 3:

export default {
  name: 'MyComponent',
  props: {
    title: {
      type: String,
      required: true,
      default: 'Default Title',
      validator: (value) => {
        return value.length <= 50;
      }
    },
    count: {
      type: Number,
      default: 0
    }
  },
  // ...
}

In the code above, we define the props option within the component's options object. The value of the props option is an object where the property names correspond to the attribute names, and the property values are objects used to specify the configuration for each attribute.

In the example, we define two attributes: title and count. The title attribute is a required string type; it has no default value and uses a custom validation function to verify that the length of the attribute value is less than or equal to 50. The count attribute is an optional number type with a default value of 0.

Attributes defined using the props option can be used in the component's template via interpolation expressions or binding syntax. For example:

<template>
  <div>
    <h1>{{ title }}</h1>
    <p>Count: {{ count }}</p>
  </div>
</template>

In the template, we can directly reference attributes defined in props, such as {{ title }} and {{ count }}.