Detailed explanation of Vue parent-child component value transfer and one-way data flow issues

Detailed explanation of Vue parent-child component value transfer and one-way data flow issues

Preface

We know that the core concept of parent-child components in Vue is the one-way data flow problem, and props are passed in one direction. So what exactly is the unidirectional data flow problem? This article summarizes the study notes on this knowledge point.

1. Parent component passes value to child component

<div id="app">
    <blog-item :title="title"></blog-item>
</div>
// Define subcomponent Vue.component("blog-item", {
      props: ['title'],
      data() {
        return {
        }
      },
      template: "<p>{{title}}</p>"
 })
// Define the parent component new Vue({
      el: "#app",
      data() {
        return {
          title: "msg",
        }
      },
    })

The parent component passes the value to the child component through :title = "title". The child component receives the value of the parent component through props and then renders it on the page through an interpolation expression.

2. Subcomponent props type constraint problem

Common type constraints are as follows:

props: {
      title: String,
      likes: Number,
      isPublished: Boolean,
      commentIds: Array,
      author: Object,
      callback: Function,
      contactsPromise: Promise // or any other constructor
    }

In addition to the common types above, Vue also provides constructors and custom functions to customize the types of child component props.

(1) Constructor custom type

//Custom function common to both components function Person (firstName, lastName) {
        this.firstName = firstName
        this.lastName = lastName
      }
      //Use Vue.component('blog-post', {
      props: {
        author: Person
      }
      //Used in parent component var obj = new Person("1","2")
      <blog-post :author='obj'></blog-post>

In the above code, we first define a public custom constructor, which can be used to create an object. The instance object has two properties, firstName and lastName. In the parent component, we call the constructor to create an obj instance and pass it to the child component. The child component defines a prop of the constructor type to receive the object.

(2) Custom functions and custom types

// Custom function Vue.component('blog-post', {
      props: {
        propsA: String, //Must be a string type propsB: [String, Number], //Multiple optional types propsC: {type: Number, default: 100}, //Define the type and set the default value //Custom validation function propsD: {
          validator: function (value) {
            // This value must match one of the following strings return ['success', 'warning', 'danger'].indexOf(value) !== -1
         }
        }
      }

Vue provides a very flexible way to define the type of parameters received by child components. In the above code, a custom validation function is used to constrain the value type in the parent component.

3. One-way data flow problem

One-way data flow is the core concept of parent-child components in Vue, and props are bound one-way. When the property value of the parent component changes, it will be passed to the child component for corresponding changes, thus forming a one-way downward binding. The property change of the parent component will flow to the downstream child component, but conversely, in order to prevent the child component from accidentally modifying the data in the parent component and affecting the status of other child components, Vue stipulates that data flow from bottom to top is not allowed.

When the property of the parent component changes, it will be passed to the child component, but the property change of the child component will not affect the parent component. In this case, you may feel that props is a bit useless. It can only be used when initializing the component and cannot be operated in the child component. Therefore, when we use it, we often have two ways to operate props: (1) define a local variable and initialize it with props, and then operate this local variable. (2) Define a computed property, process props and return it.

<div id="app">
    <blog-item :title="title1"></blog-item>
    <blog-item :title="title2"></blog-item>
    <blog-item :title="title3"></blog-item>
    <hr>
    <button @click='toclick'>Click me</button>
  </div>
  // Define subcomponent Vue.component("blog-item", {
      props: ['title'],
      data() {
        return {
        }
      },
      template: "<p>{{title}}</p>"
    })
    // Parent component new Vue({
      el: "#app",
      data() {
        return {
          title1: "111",
          title2: "222",
          title3: "333"
        }
      },
      methods: {
        toclick() {
          this.title3 = "000"
        }
      }
    }) 

<div id="app">
    <blog-item :title="title"></blog-item>
  </div>
  // Define subcomponent Vue.component("blog-item", {
      props: ['title'],
      computed: {
        computedTitle() {
          return "computedTitle" + this.title
        }
      },
      data() {
        return {
          subTitle: "subTitle" + this.title
        }
      },
      template: "<p>{{title}}==={{subTitle}}==={{computedTitle}}</p>"
    })
    // Parent component new Vue({
      el: "#app",
      data() {
        return {
          title: "111",
        }
      },
    }) 

Summarize

This is the end of this article about the value transfer between parent and child components of Vue and the one-way data flow problem. For more relevant content about the value transfer between parent and child components of Vue and the one-way data flow, please search for previous articles on 123WORDPRESS.COM or continue to browse the related articles below. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Detailed explanation of several ways to communicate and pass values ​​between components in Vue
  • How do you know how to pass values ​​between Vue components?
  • Detailed explanation of non-parent-child component value transfer in Vue3
  • Detailed explanation of value transfer between parent and child components in Vue3
  • A brief discussion on value transfer between Vue components (including Vuex)
  • Super simple and easy to understand vue component value transfer

<<:  MySQL database operations (create, select, delete)

>>:  Windows DNS server exposed "worm-level" vulnerability, has existed for 17 years

Recommend

How to use less in WeChat applet (optimal method)

Preface I am used to writing less/sass, but now I...

Use of Linux ls command

1. Introduction The ls command is used to display...

Solution to the problem of passing values ​​between html pages

The first time I used the essay, I felt quite awkw...

MySQL gets the current date and time function

Get the current date + time (date + time) functio...

Ubuntu 16.04 installation tutorial under VMware 12

This article shares with you the installation tut...

Simple usage of MySQL temporary tables

MySQL temporary tables are very useful when we ne...

How to build Git service based on http protocol on VMware+centOS 8

Table of contents 1. Cause 2. Equipment Informati...

Solution to the cross-domain problem of SpringBoot and Vue interaction

Table of contents Browser Same Origin Policy 1. V...

CSS3 uses scale() and rotate() to achieve zooming and rotation

1. scale() method Zoom refers to "reducing&q...

Example code for using HTML ul and li tags to display images

Copy the following code to the code area of ​​Drea...

vue uses Ele.me UI to imitate the filtering function of teambition

Table of contents Problem Description The general...

How to solve the problem of FileZilla_Server:425 Can't open data connection

When installing FileZilla Server on the server, t...