[Vue basic knowledge summary 7] understand parent-child components in combination with two-way binding

🍅 Java learning route: Brick movers counter attack Java Architects

🍅 Introduction: high quality creator in Java field 🏆, CSDN the author of the official account of the Na Zha ✌ , Java Architect striver 💪

🍅 Scan the QR code on the left of the home page, join the group chat, learn and progress together  

🍅 Welcome to praise 👍 Collection ⭐ Leaving a message. 📝   

catalogue

1, First experience of front-end code

1. Code example

2. Browser display

  2, Improve according to exceptions

1. Listen for events, reverse assignment

  2. Code example

3. Browser display

3, Modify the value of num1 in linkage

1. Code example

2. Browser display

4, watch

5, Parent child access through $refs

Demand analysis:

Through the input box, the two-way binding text box is displayed.

1, First experience of front-end code

1. Code example

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>

<div id="app">
  <cpn :number1="num1"
       :number2="num2"/>
</div>

<template id="cpn">
  <div>
    <h2>{{number1}}</h2>
    <input type="text" v-model="number1">
    <h2>{{number2}}</h2>
    <input type="text" v-model="number2">
  </div>
</template>

<script src="../js/vue.js"></script>
<script>
  const app = new Vue({
    el: '#app',
    data: {
      num1: 1,
      num2: 0
    },
    components: {
      cpn: {
        template: '#cpn',
        props: {
          number1: Number,
          number2: Number
        },
      }
    }
  })
</script>

</body>
</html>

2. Browser display

error message

Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead, use a data or computed property based on the prop's value. Prop being mutated: "number1"

Google translate -- >

Avoid changing prop directly because the values are overwritten whenever the parent component is re rendered. Instead, use data or calculate attributes based on the value of the prop. Item mutated: "number1"

What should I do to complete the two-way binding at this time?

The red exception is displayed. You want to define another attribute in data.

Input box binding method:

  2, Improve according to exceptions

1. Listen for events, reverse assignment

  2. Code example

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>

<div id="app">
  <cpn :number1="num1"
       :number2="num2"/>
</div>

<template id="cpn">
  <div>
    <h2>{{number1}}</h2>
    <h2>{{dnumber1}}</h2>
    <input type="text" v-model="dnumber1">
    <h2>{{number2}}</h2>
    <h2>{{dnumber2}}</h2>
    <input type="text" v-model="dnumber2">
  </div>
</template>

<script src="../js/vue.js"></script>
<script>
  const app = new Vue({
    el: '#app',
    data: {
      num1: 1,
      num2: 0
    },
    components: {
      cpn: {
        template: '#cpn',
        props: {
          number1: Number,
          number2: Number
        },
        data(){
            return{
                dnumber1:this.number1,
                dnumber2:this.number2
            }
        }
      }
    }
  })
</script>

</body>
</html>

3. Browser display

3, Modify the value of num1 in linkage

1. Code example

However, I want to pass it back to the parent component, that is, change the value of number1, that is, change num1 in data. How can I adjust it?

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>

<div id="app">
  <cpn :number1="num1"
       :number2="num2"
       @num1change="num1change"
       @num2change="num2change"/>
</div>

<template id="cpn">
  <div>
    <h2>props:{{number1}}</h2>
    <h2>data:{{dnumber1}}</h2>
    <!--<input type="text" v-model="dnumber1">-->
    <input type="text" :value="dnumber1" @input="num1Input">
    <h2>props:{{number2}}</h2>
    <h2>data:{{dnumber2}}</h2>
    <!--<input type="text" v-model="dnumber2">-->
    <input type="text" :value="dnumber2" @input="num2Input">
  </div>
</template>

<script src="../js/vue.js"></script>
<script>
  const app = new Vue({
    el: '#app',
    data: {
      num1: 1,
      num2: 0
    },
    methods: {
      num1change(value) {
        this.num1 = parseFloat(value)
      },
      num2change(value) {
        this.num2 = parseFloat(value)
      }
    },
    components: {
      cpn: {
        template: '#cpn',
        props: {
          number1: Number,
          number2: Number
        },
        data() {
          return {
            dnumber1: this.number1,
            dnumber2: this.number2
          }
        },
        methods: {
          num1Input(event) {
            // 1. Assign value in input to dnnumber
            this.dnumber1 = event.target.value;

            // 2. Issue an event so that the parent component can modify the value
            this.$emit('num1change', this.dnumber1)

            // 3. Modify the value of dnumber2 at the same time
            this.dnumber2 = this.dnumber1 * 100;
            this.$emit('num2change', this.dnumber2);
          },
          num2Input(event) {
            this.dnumber2 = event.target.value;
            this.$emit('num2change', this.dnumber2)

            // Also modify the value of dnumber2
            this.dnumber1 = this.dnumber2 / 100;
            this.$emit('num1change', this.dnumber1);
          }
        }
      }
    }
  })
</script>

</body>
</html>

2. Browser display

4, watch

The key of watch is to monitor the change of a certain attribute. It is a variant of the above writing method.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>

<div id="app">
  <cpn :number1="num1"
       :number2="num2"
       @num1change="num1change"
       @num2change="num2change"/>
</div>

<template id="cpn">
  <div>
    <h2>props:{{number1}}</h2>
    <h2>data:{{dnumber1}}</h2>
    <input type="text" v-model="dnumber1">
    <h2>props:{{number2}}</h2>
    <h2>data:{{dnumber2}}</h2>
    <input type="text" v-model="dnumber2">
  </div>
</template>

<script src="../js/vue.js"></script>
<script>
  const app = new Vue({
    el: '#app',
    data: {
      num1: 1,
      num2: 0
    },
    methods: {
      num1change(value) {
        this.num1 = parseFloat(value)
      },
      num2change(value) {
        this.num2 = parseFloat(value)
      }
    },
    components: {
      cpn: {
        template: '#cpn',
        props: {
          number1: Number,
          number2: Number,
          name: ''
        },
        data() {
          return {
            dnumber1: this.number1,
            dnumber2: this.number2
          }
        },
        watch: {
          dnumber1(newValue) {
            this.dnumber2 = newValue * 100;
            this.$emit('num1change', newValue);
          },
          dnumber2(newValue) {
            this.number1 = newValue / 100;
            this.$emit('num2change', newValue);
          }
        }
      }
    }
  })
</script>

</body>
</html>

5, Parent child access through $refs

Parent child component communication

In development, some data often needs to be sent to the upper layer and transferred to the lower layer;

For example, in a page, we request a lot of data from the server. Some of the data is not a large component of our whole page and needs to be displayed in the sub component. At this time, the sub component will not request again, but directly transfer the data from the parent component to the sub component.

So how to deliver?

Official mention:

Transfer data to sub components through props;

Pass data to the parent component through events;

It is generally not recommended to use $children, $children is generally used when getting all components.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>

<div id="app">
  <cpn></cpn>
  <cpn></cpn>

  <my-cpn></my-cpn>
  <y-cpn></y-cpn>

  <cpn ref="aaa"></cpn>
  <button @click="btnClick">Button</button>
</div>

<template id="cpn">
  <div>I am a subcomponent</div>
</template>
<script src="../js/vue.js"></script>
<script>
  const app = new Vue({
    el: '#app',
    data: {
      message: 'How do you do'
    },
    methods: {
      btnClick() {
        // 1.$children
        // console.log(this.$children);
        // for (let c of this.$children) {
        //   console.log(c.name);
        //   c.showMessage();
        // }
        // Take the content of the third component, but the subscript value is not easy to use
        // console.log(this.$children[3].name);

        // 2. $refs = > object type. The default is an empty object ref='bbb '
        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>
</html>

🍅 Java learning route: Brick movers counter attack Java Architects

🍅 Introduction: high quality creator in Java field 🏆, CSDN the author of the official account of the Na Zha ✌ , Java Architect striver 💪

🍅 Scan the QR code on the left of the home page, join the group chat, learn and progress together  

🍅 Welcome to praise 👍 Collection ⭐ Leaving a message. 📝   

Wonderful review of previous periods

[Vue basics summary 1] Introduction to Vue

[Vue knowledge system summary 2] Vue dynamic binding v-bind

[Vue knowledge system summary 3] Vue common tags

[Vue knowledge system summary 4] Vue component development

[Vue basic knowledge summary 5] Vue implements tree structure

[Vue basic knowledge summary 6] what front-end knowledge is required for Spring Boot + Vue full stack development?

Tags: Javascript Vue Vue.js html

Posted on Fri, 01 Oct 2021 21:36:30 -0400 by sivasankari.kv