vue parent-child component communication [case explanation]

Posted by leequalls on Wed, 26 Jan 2022 12:40:26 +0100

Parent component communicates with child component

The parent component wants to communicate with the child component through props in the child component

props

Type: Array | Object

Details:

props can be arrays or objects that receive data from parent components. props can be a simple array or use an object as an alternative, which allows you to configure advanced options, such as type detection, custom validation, and setting defaults.

You can use the following options based on object syntax:

  • Type: can be one of the following native constructors: String, Number, Boolean, Array, Object, Date, Function, Symbol, any custom constructor, or an Array composed of the above. It checks whether a Prop is of the given type, otherwise it throws a warning. More information about Prop types is here.
  • default: any
    Specify a default value for this prop. If the prop is not passed in, use this value instead. The default value of an object or array must be returned from a factory function.
  • required: Boolean
    Define whether this prop is required. In a non production environment, if the value is true and the prop is not passed in, a console warning will be thrown.
  • validator: Function
    The custom validation function will substitute the value of the prop as a unique parameter. In a non production environment, if the function returns a false value (i.e. verification failure), a console warning will be thrown. You can find more information about prop verification here.

Simple example:
Basic structure

  <div id="app">
    <cpn :cmovies="movies"></cpn>
  </div>

Dynamically bind cmovies of child components through v-bind, and transfer movies of parent components into cmovies of child components
cmovies in subcomponents are in props

    const cpn = {
      template: '#p1',
      props: {
        cmovies: {
          type: Array
        }
      },
      data() {
        return {}
      }
    }

movies in parent component

    const app = new Vue({
      el: '#app',
      data: {
        movies: ['dominant sea power','Iron Man']
      },
      components: {
        cpn: cpn
      }
    })


The child component successfully received the movies from the parent component

The child component communicates with the parent component

If the child component wants to pass something to the parent component, it needs to pass information through custom events

vm.$emit( eventName, [...args] )

Parameters:

  • {string} eventName
  • [...args]
    Triggers an event on the current instance. Additional parameters are passed to the listener callback
  <div id="app">
    <cpn @itemclick='cpnclick'></cpn>
  </div>

Subcomponents

  <template id="p1">
    <div>
      <button v-for="item in categories" @click="btn(item.name)">
        {{item.name}}
      </button>
    </div>
  </template>
    const cpn = {
      template: '#p1',
      data() {
        return {
          categories: [
            {id: 'aaa',name: 'Popular recommendation'},
            {id: 'bbb',name: 'Mobile digital'},
            {id: 'ccc',name: 'Household appliances'},
            {id: 'ddd',name: 'Computer office'}
          ]
        }
      },
      methods: {
        btn(item) {
          //Launch event
          this.$emit('itemclick',item)
        }
      }
    }

The btn method implementation in the child component sends data to the parent component
Each time you click this button, the name of the button is passed to the parent component

Parent component

    const app = new Vue({
      el: '#app',
      data: {
        message: 'Parent component',
      },
      components: {
        cpn: cpn
      },
      methods: {
        cpnclick(item) {
          console.log('I got it',item)
        }
      }
    })

A receiving method cpnclick(item) is defined in the parent component, and item is the received value

Bidirectional binding of parent and child components

If the value of the parent component is changed, the child component should also be changed. If the value of the child component is changed, the value of the parent component will follow this.
First look at the implementation effect:

Full code:

<!DOCTYPE html>
<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">
    <h1>Parent component data:{{num1}}</h1>
    <cpn :cnum1="num1" @smnumber1="number1"></cpn>
  </div>
  <template id="cpn">
    <div>
      <h1>Subcomponents props:{{cnum1}}</h1>
      <h1>Subcomponents smnumber1: {{smnumber1}}</h1>
      <input type="text" :value="cnum1" @input="inputnumber1">
    </div>
  </template>
  <script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>
  <script>
    const app = new Vue({
      el: '#app',
      data: {
        num1: 10
      },
      methods: {
        number1(value) {
          this.num1 = Number(value)
        }
      },
      components: {
        cpn: {
          template: '#cpn',
          data() {
            return {
              smnumber1: this.cnum1
            }
          },
          props: {
            cnum1: Number
          },
          methods: {
            inputnumber1(event) {
              this.smnumber1 = event.target.value
              this.$emit('smnumber1',this.smnumber1)
            }
          }
        }
      }
    })
  </script>
</body>
</html>

Topics: Javascript Vue