Vue custom component implements two-way binding

Vue custom component implements two-way binding

Scenario:

The interaction methods between parent and child components that we commonly use are:
The parent component flows data into the child component through props;
The child component sends the updated array to the parent component via $emit;

Today, we implement interaction in another way, referring to the v-model of the input box to implement two-way data binding of custom components.
That is, when the value of the parent component changes, the value of the child component changes accordingly; conversely, when the value of the child component changes, the value of the parent component changes accordingly

Subcomponent definition:

Since the props attribute value cannot be modified directly, we define valueData here, receive the value in real time by listening, and modify valueData through the click method.
Note that the model syntax sugar prop is the received props attribute value, which should be kept consistent. event is the name of the event passed earlier.

The code is as follows:

<template>
  <div>
    <div>{{ `Subcomponent value: ${value}` }}</div>
    <div @click="click">Click here to modify the value</div>
  </div>
</template>

<script>
export default {
  name: "",
  model: {
    prop: "value",
    event: "change"
  },
  props: {
    value: Number
  },
  components: {},
  data() {
    return {
      valueData: ""
    };
  },
  watch:
    value(newValue, oldValue) {
      this.valueData = newValue;
      console.log(`Subcomponent value: ${newValue}`);
    }
  },
  created() {
  },
  mounted() {
  },
  methods: {
    click() {
      this.valueData++;
      this.$emit("change", this.valueData);
    }
  }
};
</script>
<style lang='less' scoped>
</style>

Parent component definition:

The parent component binds the text value through v-model. The name is not necessarily value, it can be any other string that conforms to the naming convention, here it is text.
After the child component updates the data through the change event, the v-mode binding value changes accordingly.
Or when the parent component modifies the text value, the value of the child component changes accordingly.

The code is as follows:

<template>
  <div>
    <div>{{ `Parent component value: ${text}` }}</div>
    <div @click="click">Click here to modify the value</div>


    <span>-----------------------------------------------------------</span>

    <test-children v-model="text"></test-children>

  </div>
</template>

<script>
import TestChildren from "@/views/TestChildren";

export default {
  name: "",
  components: { TestChildren },
  data() {
    return {
      text: 1
    };
  },
  created() {
  },
  mounted() {
  },
  watch:
    text(newValue, oldValue) {
      console.log(`parent component value: ${newValue}`);
    }
  },
  methods: {
    click() {
      this.text--;

    }
  }
};
</script>
<style lang='less' scoped>
</style>

result:

Directly copy the code to your own project for testing. Whether the value is changed by the parent component or the child component. The values ​​of the two components bound by v-mode are always consistent.

Q&A:

A classmate asked, isn't this the same as flowing data downward through props and then passing data upward through $emit? It can also achieve the effect of two-way binding like mine. In fact, if we don’t use v-model, we will inevitably write the following code in the parent component:

<test-children @change="changeText"></test-children>

Then modify the text value by defining the changeText method.

Imagine that when our page is more complex and the number of referenced components is larger, we need to define more than ten or twenty methods like this in the page. The number of readable lines is greatly reduced, increasing maintenance costs.

Extensions:

After vue2.3, the sync method is provided, which can also realize two-way binding

Writing in the parent component:

<test-children :value.sync="text"></test-children>

The following model definition is not needed in the subcomponent, just delete it.

model: {
prop: "value",
event: "change"
},

Passing data to the parent component uses the following method:

this.$emit("update:value", this.valueData);

The above is the full content of this article. I hope it will be helpful for everyone’s study. I also hope that everyone will support 123WORDPRESS.COM.

You may also be interested in:
  • Vue2 implements component props two-way binding
  • In-depth understanding of the implementation principle of vue.js two-way binding
  • Vue2.0 uses v-model to implement a beautiful solution for component props two-way binding
  • Four ways to implement two-way binding in Vue
  • Detailed explanation of the first introductory tutorial of Vuejs (one-way binding, two-way binding, list rendering, response function)
  • How to implement two-way binding value transfer between parent and child components in Vue
  • Vue.js must learn data two-way binding every day
  • The implementation principle of two-way data binding between Angular and Vue (focusing on two-way binding of Vue)
  • How to implement two-way binding in Vue
  • Vue custom component v-model two-way binding, multiple ways to write parent-child component synchronous communication

<<:  JavaScript source code for Elimination

>>:  Detailed explanation of why v-if and v-for in Vue are not recommended to be used together

Recommend

MySQL transaction concepts and usage in-depth explanation

Table of contents The concept of affairs The stat...

Solution to 2059 error when connecting Navicat to MySQL

Recently, when I was learning Django, I needed to...

Detailed explanation of the installation steps of the MySQL decompressed version

1. Go to the official website: D:\mysql-5.7.21-wi...

Solve the problem of garbled data in MySQL database migration

Under the instructions of my leader, I took over ...

Ubuntu View and modify mysql login name and password, install phpmyadmin

After installing MySQL, enter mysql -u root -p in...

Detailed explanation of MySQL DEFINER usage

Table of contents Preface: 1.Brief introduction t...

mysql 5.7.17 winx64.zip installation and configuration method graphic tutorial

Preface: I reinstalled win10 and organized the fi...

mysql 5.7.11 winx64 initial password change

Download the compressed version of MySQL-5.7.11-w...

How to solve the slow speed of MySQL Like fuzzy query

Question: Although the index has been created, wh...

How to install docker on centos

Here we only introduce the relatively simple inst...

Solution to MySQL service 1067 error: modify the mysql executable file path

Today I encountered the MySQL service 1067 error ...

Summary of coalesce() usage tips in MySQL

Preface Recently, I accidentally discovered MySQL...

Explanation of MySQL performance inspection through show processlist command

The show processlist command is very useful. Some...

How to design MySQL statistical data tables

Table of contents Is real-time update required? M...