Table of contents
what are props
Props is a way of communication between Vue components. Through Props, the parent component can pass data to the child component, that is, the parent component can pass data to the child component through the attribute value on the component tag. Subcomponents can render and display data or perform certain operations according to their own properties and methods. Since props is a one-way data flow, it can only be passed from the parent component to the child component, and the child component cannot change the value of props, it can only be modified by the parent component. This ensures that there will be no confusion and disorder in the data transfer of components.
How to define props
In Vue components, you need to define the props of the component by configuring the props attribute. After adding the props attribute to the component, you can use the props option to receive the data passed from the parent component.
Define props using an array of strings
Props can be performed in the form of an array, where Props defines an array, each element of which is a string-type Prop name, indicating the data items that the parent component can pass to the child component.
Define props in components that do not <script setup>
use
It is very simple to declare props using a string array, just define the following in the component:
//在没有使用 `<script setup>` 的组件中定义prop
export default {
props: ['propA', 'propB', 'propC'],
setup(props) {
// setup() 接收 props 作为第一个参数
console.log(props.foo)
}
}
use
In use
<script setup>
import {
defineProps } from 'vue'
const props = defineProps(['propA', 'propB', 'propC'])
console.log(props.foo)
</script>
Define props in the form of objects
Define props, which can also be declared in the form of an object. For each property declared in the form of an object, the key is the name of the prop, and the value is the constructor function of the expected type of the prop.
Define props in components that do not <script setup>
use
// 非 <script setup>
export default {
props: {
// 确定props类型
propA: Number,
// 确定多个类型,其中可以设置默认值
propB: [String, Number],
// 自定义校验规则
propC: {
type: String,
required: true,
validator: function (value) {
return ['success', 'warning', 'danger'].indexOf(value) !== -1
}
}
}
}
use
// 使用 <script setup>
defineProps({
// 确定props类型
propA: Number,
// 确定多个类型,其中可以设置默认值
propB: [String, Number],
// 自定义校验规则
propC: {
type: String,
required: true,
validator: function (value) {
return ['success', 'warning', 'danger'].indexOf(value) !== -1
}
}
})
Props defined as objects are more flexible, and properties such as data types, validation rules, and default values can be set.
How to use props
In Vue3, using props requires the following steps:
- Declare props in component options:
props: {
propA: String,
propB: {
type: Number,
required: true
},
propC: {
type: [String, Number],
default: 'default value'
}
}
- Use props in the component's template:
<template>
<div>
<p>Prop A: {
{ propA }}</p>
<p>Prop B: {
{ propB }}</p>
<p>Prop C: {
{ propC }}</p>
</div>
</template>
- In the parent component, pass in props by binding properties:
<template>
<my-component prop-a="valueA" :prop-b="valueB"></my-component>
</template>
In the above code, "propA", "propB" and "propC" are the names of props, "String" and "Number" are the types of props, "default value" is the default value of props, "valueA" and "valueB" is the actual value passed into the props.
Usage scenarios of props
Props can be used when we need to pass data between parent components and child components. For example, in a product list page, ProductList
a , and the child component ProductItem
can receive the product information passed by the parent component through Props to render the product list. The code example is as follows
ProductList
In the parent component , define a list of products, then usev-for
the directive to traverse the list of products,ProductItem
andproduct
pass each product to the child component as a props of the child component:
<template>
<div>
<ProductItem v-for="product in products" :key="product.id" :product="product" />
</div>
</template>
<script>
import ProductItem from './ProductItem.vue'
export default {
components: {
ProductItem
},
data() {
return {
products: [
{
id: 1,
name: 'Product A',
price: 100,
description: 'This is product A'
},
{
id: 2,
name: 'Product B',
price: 200,
description: 'This is product B'
}
]
}
}
}
</script>
ProductItem
In the child component ,props
declare a propsproduct
named , and then render the product information passed by the parent component through template interpolation:
<template>
<div>
<h2>{
{ product.name }}</h2>
<p>{
{ product.description }}</p>
<p>Price: {
{ product.price }}</p>
</div>
</template>
<script>
export default {
props: {
product: {
type: Object,
required: true
}
}
}
</script>
In the above code, the parent ProductList
component products
passes the product list ProductItem
to product
the props of the child component, and the child component ProductItem
receives and renders the product information. This makes it easy to render product listings in a product listing page.
attribute validation
As mentioned earlier, Props validation can be performed by defining props
objects .
In order to verify a property, you can add a property with the same name as the property in props
the object , and the value of the property is an object. This object can contain the following options:
type
: Specifies the type of attribute. Can be a JavaScript native constructor (such as String, Number, Boolean) or a custom constructor. If multiple optional types are specified, they can be expressed in an[String, Number]
array .required
: Specifies whether the attribute is required. If the property does not have a default value, and the parent component does not pass the property, a warning will be printed in the console.default
: Specifies the default value for the property. If the property is not passed by the parent component, the default value is used.default
If the value of is an object or array, it must be set to a function and returned within the function to avoid sharing between values.validator
: Specifies a custom validator function that checks the validity of the value whenprop
it .
For example, the following component defines my-component
a component named with a prop
named age
, type Number
, and required:
<template>
<div>
<p>My age is: {
{ age }}</p>
</div>
</template>
<script>
export default {
props: {
age: {
type: Number,
required: true
}
}
}
</script>
my-component
If no age
attribute is passed or the value age
of is not a number when used, a warning will be printed to the console. If set correctly prop
, it will be passed to the component and rendered in the template.
In addition to the options mentioned above, you can props
also directly perform verification through the .default
, .required
, .type
, properties of the object, for example:.validator
<template>
<div>
<p>{
{ message }}</p>
</div>
</template>
<script>
export default {
props: {
message: {
default: 'default message',
required: true,
type: String,
validator: (value) => {
return value.length <= 10
}
}
}
}
</script>
In this example, message
the property has a default value of default message
, is required and is of type String
, and is validated using validator
the function . In this example, the validator function checks to see message
if is more than 10 characters, and if so, returns false and prints a warning.
Non-prop attributes
Sometimes the parent component may pass some non-props properties specific to the child component. Non-Prop properties refer to properties that are used in the component but not defined props
in . These properties can be used as template placeholders or as classname and style bindings in component templates. For example passing CSS class names or event listeners. These non-prop properties can $attrs
be accessed .
$attrs
: Contains attribute bindings that are not considered props in the parent scope (except class and style). When a component is created, all attributes (except those already defined in props) are automatically added to$attrs
the object .
For example, in the following code, a MyComponent
component , which defines two prop
( message
and color
) and one non- prop
properties title
. This component renders a element props
with the value of <div>
and binds the non prop
attribute to the element:
<template>
<div :style="{ color }" :title="title">
{
{ message }}
</div>
</template>
<script>
export default {
props: {
message: {
type: String
},
color: {
type: String,
default: 'black'
}
},
setup(props, {
attrs }) {
// 获取非 prop 特性 title 的值
const title = attrs.title
return {
title
}
}
}
</script>
In the above code, we use $attrs
the object to get the value ofprop
non-property and expose it to the component template. title
For example, if we use MyComponent
the component :
<MyComponent message="Hello world" color="red" title="This is a title" />
will render a red <div>
element with a title
attribute. Since title
is not one prop
, we need to use $attrs
the object to get its value.
Unidirectional data flow feature
In Vue components, props are one-way data flow. This means, data can only be passed from parent to child components, not the other way around. Such features can reduce the confusion and disorder of data transmission, and also make the data flow more intuitive and easy to maintain.
In child components, you cannot directly change the value of Props passed from the parent component. If you need to change the value of Props, you should use events, etc., such as passing the modified information to the parent component through $emit
the method , so that the parent component can change the data.
default properties of props
The default feature of Props is designed to handle default values. Normally, Props receive the data passed from the parent component, but sometimes if the parent component does not pass data, you need to use the default value. When defining Props, you can use default
the option to specify a default value for the Props.
For example:
props: {
message: {
type: String,
default: 'Hello, Vue!'
}
}
In the above code, message
the default value is set for Props Hello, Vue!
. If the parent component does not pass message
data , message
the value of props will be the default value Hello, Vue!
.
In addition, the parent component can also dynamically bind the value of Props v-bind
by . For example:
<template>
<example-component v-bind:message="dynamicMessage"></example-component>
</template>
<script>
export default {
data() {
return {
dynamicMessage: '动态绑定的消息'
}
}
}
</script>
In the above code, dynamicMessage
it is the data in the parent component, which is used to dynamically bind the value of Props. In child components, you can use props.message
to access the data passed by the parent component.
Well, that’s the end of the detailed introduction about Props in vue. If you have any questions, leave a message in the comment area.