Complex bidirectional bindings implemented between parent and child components

One requirement: You now have two inputs in the component, and you need to implement bidirectional binding of inputs (and change the data value of the parent component), and output the value of the second input as 100 times the second value.

Technical points used: parent-child component communication, bidirectional binding of forms

It is worth mentioning that we do not recommend putting the props values directly in the model when we use the model, because this value is passed from the parent component, so it might be messy to change it directly. Therefore, we need to use the data property of the component to do worthy binding;

To change the properties of data, we can pass the component’s data to the parent and then modify the value of the parent’s data. In this way, we can also modify the parent’s data and the related values of the child component’s props.

The final requirement is 100x, which also listens when our input event fires, then evaluates, and then passes via emit

<! DOCTYPEhtml>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
  <title>Document</title>
</head>

<body>
  <div id="app">
    <mycon :cnum1='num1' :cnum2='num2' @event1='event1' @event2='event2'></mycon>
  </div>
  <template id="cpm">
    <div>
      <p>props:{{cnum1}}</p>
      <p>data:{{copycnum1}}</p>
      <input type="text" name="" id="" :value='copycnum1' @input='docopycnum1'>
      <p>props{{cnum2}}</p>
      <p>data{{copycnum2}}</p>
      <input type="text" name="" id="" :value='copycnum2' @input='docopycnum2'>
    </div>
  </template>
</body>
<script src=".. /vue.js"></script>
<script>
  var cpm = {
    template: '#cpm'.props: {
      cnum1: Number.cnum2: Number,},data() {
      // The official recommended practice
      return {
        copycnum1: this.cnum1,
        copycnum2: this.cnum2,
      }
    },
    methods: {
      docopycnum1(event) {
        this.copycnum1 = event.target.value;
        this.$emit('event1'.this.copycnum1);
        this.copycnum2=this.copycnum1*100
        this.$emit('event2'.this.copycnum2)
      },
      docopycnum2(event) {
        this.copycnum2 = event.target.value;
        this.$emit('event2'.this.copycnum2)
        this.copycnum1=this.copycnum2/100
        this.$emit('event1'.this.copycnum1)
      }
    },
  }
  new Vue({
    el: '#app'.data: {
      num1: 0.num2: 0
    },
    components: {
      mycon: cpm
    },
    methods: {
      event1(data) {
        this.num1 = parseFloat(data);
      },
      event2(data) {
        this.num2 = parseFloat(data); }}})</script>

</html>
Copy the code