Tommy

Tommy

写代码是热爱,但也是生活 !
github

this.$emit: Vue parent-child component communication

Communication between child components and parent components in Vue requires the use of this.$emit(). Let's first review how communication between parent and child components is done.#

1. Passing values from parent component to child component: Data is passed through v-bind: (which can be simplified as a colon), and the child component uses props to receive it.
For example:
// Parent component
<todo-item v-bind:item="item"
           v-bind:index="index"
           v-for="(item,index) in list"></todo-item>
// Child component
var TodoItemValue = {
        props: ['item','index'],// 'item' and 'index' are passed from the parent component through v-bind
        template:"<li>{{item}}{{index}}</li>"
    } 
2. How about passing values from child component to parent component? This is where we need to use this.$emit() method.

The basic process of passing values from child component to parent component is as follows:#

Step 1: Import the child component into the parent component#

  1. Use import to import the component
  import indexImportOrder from './components/indexImportOrder'
  1. Declare the component
// Define the component
components:{
  indexImportOrder,
},
  1. Use the component
<indexImportOrder ref="indexImportOrder"/>

Step 2: Child component passes values to parent component#

  1. In the child component, use this.$emit("function", param) at the place where you need to pass values to the parent component.
    Where "function" is the function defined in the parent component, and "param" is the parameter to be passed
// Jump to the new order page
viewBusiness(){
  let flag = false;
  this.$emit('closeMain',flag);
},
  1. In the parent component, add the function v-on="function1" to the reference of the child component.
    Where "function" is the function defined in the child component, and "function1" is the function defined in the parent component to receive the passed value and perform corresponding data processing. They can be defined with the same name

    v-on: can be replaced with @, @function="function1" is the shorthand for v-on="function1"
<indexImportOrder ref="indexImportOrder" v-on:closeMain="closeMain"/>
  1. val is the flag in the child component, which is the received parameter from the child component
closeMain(val){
  this.flag = val;
},

Done#

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.