Vue3 props Property
props is a way to pass data between components.
In Vue.js, the parent component can pass data to the child component via props . After receiving this data, the child component can render based on it or perform other operations.
An Analogy
You can think of props as a postman. The parent component is the sender and the child component is the recipient. The parent passes data (a letter) to the child via props(the postman). After receiving the data, the child component can process it based on its content.
How to Use props?
Using props in Vue.js is very simple. Below we use an example to illustrate how to use props.
Example: Passing and Receiving props
Suppose we have a parent component ParentComponent and a child component ChildComponent. We want the parent component to pass a message to the child component.
1. Parent Component (ParentComponent.vue)
Example
2. Child Component (ChildComponent.vue)
Example
{{ message }}
Explanation
-
Parent component: In the parent component, we pass the
:message="parentMessage"data to the child component viaparentMessage.parentMessageis a variable defined in the parent component with the value'Hello from Parent!'. -
Child component: In the child component, we use
propsto receive the data passed from the parent component.messageis aprops, whose type isStringand set torequired: true, indicating thispropsis required. -
Rendering: After the child component receives the
message, it renders it into the template, displaying.Hello from Parent!
props Types and Validation
In Vue.js, you can specify types and validation rules for props to ensure the passed data meets expectations.
Example: Types and Validation
Example
props
:
{
message
:
{
type
:
String
,
required
:
true
}
,
age
:
{
type
:
Number
,
default
:
18
}
,
hobbies
:
{
type
:
Array
,
validator
:
function
(
value
)
{
return
value.
length
0
;
}
}
}
Explanation
-
**
type**: Specifies thepropsdata type. Can beString,Number,Boolean,Array,Object, etc. -
**
required**: Specifies thepropswhether it is required. If set totrue, the parent component must pass thisprops, otherwise a warning is thrown. -
**
default**: Sets a default value forprops. If the parent component does not pass thisprops, the child component will use the default value. -
**
validator**: A custom validation function used to validatepropsvalue meets specific conditions.
Notes
-
One-Way Data Flow: In Vue.js,
propsis one-way, meaning data can only flow from the parent component to the child component. The child component should not directly modify thepropsvalue. If modification is needed, it can notify the parent component to make the change by emitting an event. -
Naming Convention:
props's naming is recommended to use camelCase, for exampleuserName. When passingpropsin the parent component, kebab-case is recommended, for exampleuser-name. -
Dynamic props: You can dynamically bind
v-bindor:usingprops, for example:message="parentMessage".
Vue3 Options API