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

Syntax alias problem based on delete in mysql

Table of contents MySQL delete syntax alias probl...

A brief discussion on HTML ordered lists, unordered lists and definition lists

Ordered List XML/HTML CodeCopy content to clipboa...

Three implementation methods of Mysql copy table and grant analysis

How to quickly copy a table First, create a table...

Steps to deploy multiple tomcat services using DockerFile on Docker container

1. [admin@JD ~]$ cd opt #Enter opt in the root di...

Brief analysis of the introduction and basic usage of Promise

Promise is a new solution for asynchronous progra...

HTML table tag tutorial (13): internal border style attributes RULES

RULES can be used to control the style of the int...

Clever use of webkit-box-reflect to achieve various dynamic effects (summary)

In an article a long time ago, I talked about the...

CSS to achieve Skeleton Screen effect

When loading network data, in order to improve th...

How to use partitioning to optimize MySQL data processing for billions of data

When MySQL queries tens of millions of data, most...

How to hide the version number and web page cache time in Nginx

Nginx optimization---hiding version number and we...

Detailed Example of Row-Level Locking in MySQL

Preface Locks are synchronization mechanisms used...

How to connect to MySQL visualization tool Navicat

After installing Navicat The following error may ...