Vue parent component passes value to child component

When we split the whole page into different components, it will involve the problem of data transfer between components.

The communication of common components can be divided into three categories:

The first type: the parent component transfers data to the child component

The second type: the child component passes data to the parent component

The third category: data transfer of brother components.

Next, let's take a look at the transfer of data from the parent component to the child component

First: the subcomponent receives the passed value through props.

Vue.component('menu-item',{
 props:['title'] // props is followed by an array. The contents of the array are strings, which can be used as attribute classes.
 template:'<div>{{title}}</div>'   
})

Second: the parent component passes the value to the child component through the attribute

<menu-item title="Transfer data to subcomponents"> </menu-item>
<menu-item :title="title"></menu-item> <!--You can use dynamic binding to pass values-->

Let's take a look at the specific case demonstration:

<body>
    <div id="app">
        <father></father>
    </div>
    <script>
        // Create a parent component
        Vue.component('father', {
            // 2. Where a sub component is used, the props in the sub component is assigned a value through the v-bind instruction.
            template: '<div><p>I am the parent component</p><son :myName="mySonName"></son></div>',
            data() {
                return {
                    mySonName: 'cockroach'
                }
            },
            components: {
                // Create a sub component
                // 1. Declare props, which is used to receive the data passed by the parent component.
                // props can be followed by an array. The contents of the array can be strings, which can be used as attributes.
                son: {
                    props: ['myName'],
                    template: '<p>I am a subcomponent,My name is{{myName}}</p>'
                }
            }
        })
        var vm = new new Vue({
            el: '#app',
            data: {
​
            }
        })
    </script>
</body>

Let's take a look at an example. This example is the case of local components we wrote earlier. We realize the value transfer of components on the basis of this case.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Local component</title>
    <script src="./vue.js"></script>
  </head>
  <body>
    <div id="app">
      <father></father>
      <component-a></component-a>
      <hello-msg title="Hello" :pcontent="content"></hello-msg>
    </div>
    <script>
      const son = {
        data() {
          return {
            msg: "Hello I am a subcomponent",
          };
        },
        template: `<div>{{msg}}</div>`,
      };
      // Define HelloMsg components
      const HelloMsg = {
        props: ["title", "pcontent"],
        data() {
          return {
            msg: "Hello World",
          };
        },
        template: `<div>{{msg+'----------'+title+'-----------'+pcontent}}</div>`,
      };
      Vue.component("ComponentA", {
        template: "<div><son></son></div>",
        components: {
          son: son,
        },
      });
      Vue.component("father", {
        template: "<div><p>I am the parent component</p><son></son></div>",
        components: {
          // Create a sub component
          //   son: {
          //      Template: "< p > I am a sub component < / P >",
          //   },
          son: son,
        },
      });
      var vm = new Vue({
        el: "#app",
        data: {
          content: "Content from parent component",
        },
        components: {
          "hello-msg": HelloMsg,
        },
      });
    </script>
  </body>
</html>
​

In the above code, we first pass a property title to the Hello MSG component, and the value of the property is fixed. Define props in the corresponding HelloMsg component content to receive the passed value of the title attribute. Then display the value of title in the template template.

Next, a content attribute is specified in the vue instance. Next, the value of this attribute will be passed to the HelloMsg component.

<hello-msg title="Hello" :pcontent="content"></hello-msg>

Here, the value of content needs to be passed to the HelloMsg component by dynamic binding. Here, the dynamically bound attribute is pcontent, so inside the HelloMsg component, you need to add a pcontent to the props array, and finally display the content of pcontent in the template template.

 // Define HelloMsg components
      const HelloMsg = {
        props: ["title", "pcontent"],
        data() {
          return {
            msg: "Hello World",
          };
        },
        template: `<div>{{msg+'----------'+title+'-----------'+pcontent}}</div>`,
      };

Through the above case, we can see that props can be used in the child component to receive the data passed from the parent component.

However, props has certain rules when naming.

If the hump form is used in props, the form of short horizontal line is required in the template, as shown in the following code case:

Vue.component('menu-item',{
    //Hump form in JavaScript
    props:['menuTitle'],
    template:'<div>{{menuTitle}}</div>'
})
<!--stay html The middle is the short horizontal line mode--->
    <menu-item menu-title="hello world"></menu-item>

Let's take a look at the specific code demonstration:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Component value transfer</title>
  </head>
  <body>
    <div id="app">
      <menu-item :menu-title="ptitle"></menu-item>
    </div>
    <script src="./vue.js"></script>
    <script>
      Vue.component("menu-item", {
        props: ["menuTitle"],
        template: `<div>come from{{menuTitle}}</div>`,
      });
      const vm = new Vue({
        el: "#app",
        data: {
          ptitle: "Data in parent component",
        },
      });
    </script>
  </body>
</html>

Let's take a look at the types of props attribute values.

props can receive various types of values.

As follows:

String (string)

Value (Number)

Boolean

Array

Object

Next, demonstrate the above types:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>props type</title>
  </head>
  <body>
    <div id="app">
      <menu-item
        :str="str"
        :num="10"
        b="true"
        :marr="arr"
        :obj="obj"
      ></menu-item>
    </div>
    <script src="./vue.js"></script>
    <script>
      Vue.component("menu-item", {
        props: ["str", "num", "b", "marr", "obj"],
        template: `<div>
                <div>{{str}}</div>
                <div>{{typeof num}}</div>
                <div>{{typeof b}}</div>
                <div>
                   <ul>
                    <li :key=item.id v-for='item in marr'>{{item.userName}}</li>
                   </ul>
               </div>
               <div>
                full name: {{obj.name}}
                Age:{{obj.age}}
                </div>
                </div>`,
      });
      const vm = new Vue({
        el: "#app",
        data: {
          str: "hello",
          arr: [
            { id: 1, userName: "zhangsan" },
            {
              id: 2,
              userName: "lisi",
            },
          ],
          obj: {
            name: "wangwu",
            age: 18,
          },
        },
      });
    </script>
  </body>
</html>

In the above code, various types of data are passed to the menu item component.

be careful:

  
<menu-item :str="str" :num="10" b="true" :marr="arr"></menu-item>

In the above code,: num="10" means that the number is passed. If it is written as num="10"   Indicates that characters are passed,

Similarly, b="true" passes characters. If it is modified to: b=true, it means that the passed type is Boolean.

Finally, the contents of array type and object type are passed.

Tags: Vue.js

Posted on Thu, 23 Sep 2021 19:25:02 -0400 by chrisprse