Know Props in vue

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:

  1. Declare props in component options:
props: {
    
    
  propA: String,
  propB: {
    
    
    type: Number,
    required: true
  },
  propC: {
    
    
    type: [String, Number],
    default: 'default value'
  }
}
  1. 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>
  1. 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, ProductLista , and the child component ProductItemcan receive the product information passed by the parent component through Props to render the product list. The code example is as follows

  1. ProductListIn the parent component , define a list of products, then use v-forthe directive to traverse the list of products, ProductItemand productpass 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>
  1. ProductItemIn the child component , propsdeclare a props productnamed , 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 ProductListcomponent productspasses the product list ProductItemto productthe props of the child component, and the child component ProductItemreceives 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 propsobjects .

In order to verify a property, you can add a property with the same name as the property in propsthe 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. defaultIf 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 when propit .

For example, the following component defines my-componenta component named with a propnamed 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-componentIf no ageattribute is passed or the value ageof 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 propsalso 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, messagethe property has a default value of default message, is required and is of type String, and is validated using validatorthe function . In this example, the validator function checks to see messageif 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 propsin . 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 $attrsbe 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 $attrsthe object .

For example, in the following code, a MyComponentcomponent , which defines two prop( messageand color) and one non- propproperties title. This component renders a element propswith the value of <div>and binds the non propattribute 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 $attrsthe object to get the value ofprop non-property and expose it to the component template. titleFor example, if we use MyComponentthe component :

<MyComponent message="Hello world" color="red" title="This is a title" />

will render a red <div>element with a titleattribute. Since titleis not one prop, we need to use $attrsthe 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 $emitthe 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 defaultthe option to specify a default value for the Props.
For example:

props: {
  message: {
    type: String,
    default: 'Hello, Vue!'
  }
}

In the above code, messagethe default value is set for Props Hello, Vue!. If the parent component does not pass messagedata , messagethe value of props will be the default value Hello, Vue!.

In addition, the parent component can also dynamically bind the value of Props v-bindby . For example:

<template>
  <example-component v-bind:message="dynamicMessage"></example-component>
</template>
<script>
export default {
  data() {
    return {
      dynamicMessage: '动态绑定的消息'
    }
  }
}
</script>

In the above code, dynamicMessageit is the data in the parent component, which is used to dynamically bind the value of Props. In child components, you can use props.messageto 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.

Guess you like

Origin blog.csdn.net/w137160164/article/details/131104905