vueJs parent-child component communication

Parent child component communication Child components cannot reference the data of parent components or Vue instances. ...
Parent child component communication
  • Child components cannot reference the data of parent components or Vue instances.
  • However, during development, some data often needs to be transferred from the upper layer to the lower layer:
  • For example, in a page, we request a lot of data from the server.
  • Some of the data is not displayed by the large components of our whole page, but by the following sub components.
  • At this time, the sub component will not send a network request again, but directly let the large component (parent component) pass the data to the small component (sub component).
    How to communicate between parent and child components? Vue official mentioned
    • Pass data to subcomponents through props
    • Send messages to parent components through events

Pass function (props) from parent component to child component

There are two ways to the value of props:

  • Method 1: string array. The string in the array is the name when passing.
  • Method 2: object. The object can set the type during transmission, or set the default value, etc
  • The details are shown in the following code
<body> <div id="app"> <cpn :cmessage="message" :cmovies="movies"></cpn> </div> <template id="cpn"> <div> <ul> <li v-for="item in cmovies">{}</li> </ul> <h2>{}</h2> </div> </template> <script src="../vue.js"></script> <script> // Father to son: props const cpn = { template: "#cpn", props: { //1. Type restrictions // 2. Provide some default values and required values cmovies: { type: Array, default() { return []; }, }, cmessage: { type: String, default: "aaaaaa", required: true, }, }, }; const app = new Vue({ el: "#app", data: { message: "How do you do", movies: ["Hello", "One Piece", "Sorrow flows upstream into a river"], }, components: { cpn, }, }); </script> </body>

props data validation

Earlier, our props option was to use an array.
We said that in addition to arrays, we can also use objects. When we need to verify the type of props, we need object writing.
What data types are supported for validation?
String
Number
Boolean
Array
Object
Date
Function
Symbol
When we have a custom constructor, validation also supports custom types

Child component passes ($emit) to parent component

props is used to transfer data from the parent component to the child component. Another common method is that the child component transfers data or events to the parent component.
How should we deal with it? At this time, we need to use custom events to complete.
When do I need to customize events?

  • When a child component needs to pass data to the parent component, a custom event is used.
  • The v-on we learned earlier can be used not only for listening to DOM events, but also for custom events between components.
    Custom event flow:
    • In the subcomponent, $emit() is used to trigger events.
    • In the parent component, listen for child component events through v-on.
    • Let's take a simple example:
    • Two buttons + 1 and - 1. Click to modify counter.
    • The whole process of our operation is still completed in the child component, but the subsequent display is handed over to the parent component.
      In this way, we need to pass the counter in the child component to a property of the parent component, such as total.
<body> <div id="app"> <cpn @item-click="cpnClick"></cpn> </div> <template id="cpn"> <div> <button v-for="item in categories" @click="btnClick(item)"> {} </button> </div> </template> <script src="../vue.js"></script> <script> const cpn = { template: "#cpn", data() { return { categories: [ { id: "aaa", name: "Popular recommendation" }, { id: "bbb", name: "Mobile digital" }, { id: "ccc", name: "Household appliances" }, { id: "ddd", name: "Computer office" }, ], }; }, methods: { btnClick(item) { // Launch events: custom events this.$emit("item-click", item); }, }, }; // 2. Parent component const app = new Vue({ el: "#app", data: { message: "How do you do", }, components: { cpn, }, methods: { cpnClick(item) { console.log("cpnClick", item); }, }, }); </script> </body>
Access mode of parent-child components

Sometimes we need the parent component to directly access the child component, the child component to directly access the parent component, or the child component to access the root component.

  • Parent component accesses child components: use $children or $refs

    Defects of $children:

    • When accessing subcomponents through $children, it is an array type, and the subcomponents must be accessed through the index value.
      However, when there are too many subcomponents and we need to get one of them, we often can't determine its index value, and even may change.
      Sometimes, when we want to explicitly obtain one of the specific components, we can use $refs

      Use of $refs:
      The $refs and ref instructions are usually used together.

    • First, we bind a specific ID to a sub component through ref.

    • Secondly, you can access the component through this.$refs.ID.

    <body> <div id="app"> <cpn ref="aaa"></cpn> <cpn></cpn> <cpn></cpn> <button @click="btnClick">Button</button> </div> <template id="cpn"> <div>I am a subcomponent</div> </template> <script src="../vue.js"></script> <script> const app = new Vue({ el: "#app", data: { message: "How do you do", }, methods: { btnClick() { // console.log(this.$children); // for (let c of this.$children) { // console.log(c.name); // c.showMessage(); // } // console.log(this.$children[0].showMessage); console.log(this.$refs); console.log(this.$refs.aaa.name); }, }, components: { cpn: { template: "#cpn", data() { return { name: "I'm a subcomponent name", }; }, methods: { showMessage() { console.log("showMessage"); }, }, }, }, }); </script> </body>
  • Child component accessing parent component: use $parent

    • Although in Vue development, we allow access to parent components through $parent, we try not to do so in real development.

    • Child components should try to avoid directly accessing the data of the parent component, because the coupling is too high.

    • If we put a child component in another component, it is likely that the parent component has no corresponding properties, which often causes problems.

    • In addition, it is even worse to directly modify the state of the parent component through $parent. Then the state of the parent component will become erratic, which is not conducive to my debugging and maintenance.

4 November 2021, 20:09 | Views: 8193

Add new comment

For adding a comment, please log in
or create account

0 comments