current position:Home>$emit child to parent data in Vue component communication

$emit child to parent data in Vue component communication

2022-01-26 23:35:20 huxiaoxiao.

Son father

In the sub assembly adopt $emit(' Custom event name ', Variable 1, Variable 2) Trigger event

Parent component @ Custom event name =' Event name ' Monitoring events

After the event is triggered , adopt $emit To trigger Parent component Bound to the sub component label Custom events

Parameters 1: The event to trigger

Parameters 2: The value to pass

Subcomponent methods this.$emit('sendfather',val1,val2) Trigger custom event

In the parent component <child @wyf="getMsgFromSon"></child>


1. First, there is a data in the sub component

let one  ={
            template:`#one`,
            data(){
                return {
                    mes:' Data sending parent component ',
                }
            }
        }

2. Write a button on the view layer of the sub component , And add a click method :

<template id="one">
        <div>
            <h1> I am a subcomponent one</h1>
            <button @click="add()"> Send data to parent component </button>
        </div>
    </template>
 methods:{
                add(){
                    //  The front name here is customized , Send data on behalf of 
                    //  The following is the data to be sent 
                    this.$emit('getmes',this.mes)
                // As long as this event triggers , The data is sent out 
                }
            }

3. Write a method in the parent component , And bind this method where sub components are used on the view layer of the root component :

data:{
                message:''
            }, 
methods:{
                //  At this point data It is the data of the sub components sent 
                setmes(data){
                    // Assign data to your own data center message
                    this.message = data;
                    console.log(this.message);  
                }
<!--  Bind the method with the custom name as the parent component  -->
        <one @getmes="setmes"></one>

Render this data in the root component , When the button is clicked :

 

copyright notice
author[huxiaoxiao.],Please bring the original link to reprint, thank you.
https://en.cdmana.com/2022/01/202201262335171212.html

Random recommended