When a child component uses this.$emit() to send a value to its parent, it must first reference the child component in the parent and then implement the emit.

The first step is to introduce child components into the parent component

Import Import components using import

import indexImportOrder from './components/indexImportOrder'
Copy the code

The statement

// Define component Components :{indexImportOrder,},Copy the code

use

<indexImportOrder ref="indexImportOrder"/>
Copy the code

Step 2 The child passes the value to the parent

$emit(“function”,param); Function is the same as the function name after @ in the parent component, param is the parameter that needs to be passed.

Where the parent refers to the child, add the function V-on :function=”function1″; Function specifies the same function name for the child component, and function1 specifies the function for the parent component (used to receive values from the child component and perform corresponding data processing) V-on: can be replaced by @. @function=”function1″, @ is short for V-on:.

<indexImportOrder ref="indexImportOrder" @closeMain="closeMainPar"/>
Copy the code

Val is the received subcomponent parameter,

closeMainPar(val){
  this.flag = val;
},
Copy the code

In vue we often use v-bind(abbreviated 🙂 to pass arguments to child components. Or we might pass a function to a child component, which changes the state of the parent component by calling the function. Such as:

// The parent passes a function to the child <MyFooter :age="age" @setage ="(res)=> age= res"> </MyFooter> the child calls this function to modify the state of the parent. mounted () { console.log(this.$emit('setAge',1234567)); }Copy the code

The child triggers the parent’s change function, changing the age of the parent to 1234567.

It’s a little bit more common and it’s a little bit more complicated. Which brings us to today’s hero.sync.

So we could just write it like this

// The parent passes age to the child and uses the.sync modifier. Data binding synchronizes the child's age property with the parent's age property. <MyFooter :age. Sync ="age"> </MyFooter> // Console. log(this.$emit('update:age',1234567)); // MyFooter :age ="age"> </MyFooter> // Console. log(this. }Copy the code

Notice here that our event name has been changed to update:age

  • Update: is fixed, which is the part of the name that Vue has agreed for us.
  • Age is the name of the state we want to change, which we manually configure to correspond to the name of the state passed in.

That’s it. Doesn’t it feel a lot easier.

Note: We must prefix the event execution name with update: to properly fire the event.