Vue.js component communication - parent component passes value to child component - through props

Component Communication Overview

Although there is a parent-child relationship between components, they are still independent of each other. They cannot directly manipulate each other's data. This is for security reasons. There is a need for communication between components , and Vue provides us with two ways to achieve communication between parent and child components. They are props (father to son) and emit (child to father). It will be explained in detail later.

Component communication is a very important and relatively difficult content, so it needs more practice and mastery.

The author intends to write two articles to introduce props (father-to-son) and emit (child-to-father) respectively. This article first introduces the use of props (father-to-son).

Tucao about official documents (you can skip to the next section)

Off topic, you can skip to the next section.

If you have read the official documentation, props is described as a node alone, and then you find that you can’t understand it at all, and you don’t know what he is talking about. And as soon as we come up, we will talk about the hump naming of props. It's not your problem, it's the documentation's problem.
At the very beginning of the document, there is a section telling you to read the component basics first. Indeed, in the component foundation section, the definition of props is actually given.
insert image description here

This is the most incomprehensible document structure for me, put the definition somewhere else, and write the unimportant stuff at the beginning of a separate node.
insert image description here
My suggestion is to read the part about props definition in the component foundation first, and then read the props section.

what are props

The function of parent-to-child communication in component communication is realized through props. So what are props?

Props are custom attributes that you can register on components. This is the official definition. To put it simply, when the parent component passes the value to the child component, the value is directly passed to the property defined by the child component itself. These properties (properties) are defined in the subcomponents, yes, prop is the abbreviation of property. It is equivalent to a box with a name for the parent component, just ask the parent component to put data in it.

Or give an example to illustrate more clearly.
We define a template for a child component, because the child component is provided to the parent component (usually the top-level component). Therefore, the variables defined by the child components cannot be hard-coded, but need to be passed in by the parent component.

<!--1.定义子组件模板-->
<template id="studentInfo">
    <div>
        <p>{
    
    {
    
    msg}}</p>
        <p>姓名:{
    
    {
    
    name}}</p>
        <p>年龄:{
    
    {
    
    age}}</p>
        <p>性别:{
    
    {
    
    gender}}</p>
    </div>
</template>

We want the parent component to have a similar effect when using child components.
If you run the code, you will definitely report an error, because we have not defined the name, age and gender attributes at all.
Here is the most critical place. What should I do? Of course it is defined in the subcomponent.

<div id="box">
       <student name="张三" age="age" gender="男"></student>
       <hr>
       <student name="李四" age="18" gender="女"></student>
</div>

We can define the properties of subcomponents by writing props in subcomponents.
This is the key point.
The essence of props is to define the name of the property for the component.
The essence of props is to define the name of the property for the component.
The essence of props is to define the name of the property for the component.

Writing values ​​to props is equivalent to using the template tags of subcomponents as shown below. At this time, no error will be reported, because name, age, and gender have already been defined.

 <student name="xxx" age="xxx" gender="xxx"></student>

Data is also defined here, which returns the value of msg. That is, msg is the value of the child component itself, which is not exposed to the parent component.

<!--2.注册子组件-->
  Vue.component("student",{
    
    
      template:`#studentInfo`,
      data(){
    
    
          return{
    
    
             msg: "我是一个好学生"
          }
       },
      //3.定义属性
      props:["name","age","gender"]
  })

A magical thing happened when the code was run. The name, age, and gender attributes that did not exist originally were available.

<student name="李四" age="18" gender="女"></student>

insert image description here

Multiple definitions of props

The first way:
This is the easiest way.

props:["name","age","gender"]

The second way:
relatively standardized.

      props:{
    
    
          name:String,
          age:Number,
          gender:String
      }

The third way:
the most complete usage.

      props:{
    
    
          name:{
    
    
              type:String,
              required:true
          },
          age:{
    
    
              type:Number,
              required: false,
              default:99
          },
          gender: {
    
    
              type:String
          }
      }

props and data binding

In fact, the basic concept of props has been explained earlier. Next, let's look at the problems encountered in use.

Now I want the value passed by age to be automatically incremented by 1. It is possible to write the following code, but this is wrong. The result is as follows, which becomes the addition of two strings.

<!--1.定义子组件模板-->
<template id="studentInfo">
    <div>
        //some code
        <p>年龄:{
    
    {
    
    age+1}}</p>
        //some code
    </div>
</template>

insert image description here
In fact, it is very simple, we only need to set the age as data binding. A little trick of data binding is involved here. After data binding, the content inside " " becomes an expression instead of a string, so that the age content becomes the Number type when it is transmitted.

 <student name="张三" :age="18" gender="男"></student>

Under normal circumstances, when passing values, we will not write directly, but pass values ​​through data. We define two values.

    var app = new Vue({
    
    
        el: "#box",
        data: {
    
    
            message:"你叫什么名字",
            age:25
        },
        methods: {
    
    }
    })

Bind these two values ​​​​through data binding.

<student :msg="message" name="张三" :age="18" gender="男"></student>

We did not define the msg attribute, so an error will be reported. At this time, we need to define the msg attribute in props.

 props:["name","age","gender","msg"]

In this way, our msg is also transmitted.
insert image description here
If you open the console, you will find that an error has been reported. Although the interface is still normal. will tell you the error below. Because the parent component is passing the value now, just annotate the following code directly, write it into props, and assign the default value.
insert image description here
data can be commented.

      data(){
    
    
          return{
    
    
             // msg: "我是一个好学生"
          }
      }

Set default value for msg.

          msg:{
    
    
              type:String,
              default: "我是一个好学生"
          }

Modify the value passed from the parent component

Now add two buttons, for age++ and –

<template id="studentInfo">
    <div>
        <p>{
    
    {
    
    msg}}</p>
        <p>姓名:{
    
    {
    
    name}}</p>
        <p>年龄:{
    
    {
    
    age}}</p>
        <p>性别:{
    
    {
    
    gender}}</p>
        <button @click="age++">+</button>
        <button @click="age--">-</button>
    </div>

</template>

The functionality is available, but with the following caveats. The general meaning is to avoid modifying the value passed by the parent component, because the parent and child components may be modified at the same time, which will cause some problems.
insert image description here
But what if I need to implement such a function? Consider buffering with an intermediate variable.

     data(){
    
    
          return{
    
    
              myAge:this.age
          }
      }

Then we can operate on our intermediate variables.

        <p>年龄:{
    
    {
    
    myAge}}</p>
        <button @click="myAge++">+</button>
        <button @click="myAge--">-</button>

Summarize

The meaning of props itself is an attribute. It is used to define properties for subcomponents. The child component has properties, and the parent component can directly assign values ​​to these properties.

Guess you like

Origin blog.csdn.net/ScottePerk/article/details/126964678
Recommended