Vue parent-child component transfer non-parent-child component transfer

1. The parent component passes data to the child component
How to pass data from parent component to child component? This can be achieved through the props attribute

Parent component:

<parent>
    <child :child-msg="msg"></child>//You must use - instead of camel case here
</parent>

data(){
    return {
        msg: [1,2,3]
    };
}
Child components receive data via props:

Way 1:
props: ['childMsg']

Method 2 :
props: {
    childMsg: Array //This can specify the incoming type, if the type is incorrect, a warning will be issued
}

Way 3:
props: {
    childMsg: {
        type: Array,
        default: [0,0,0] //This can specify the default value
    }
}
In this way, the parent component can pass data to the child component.

2. The child component communicates with the parent component
So what if the child component wants to change the data? This is not allowed in Vue, because Vue only allows one-way data transfer. At this time, we can notify the parent component to change the data by triggering an event, so as to achieve the purpose of changing the data of the child component.

Subassembly:
<template>
    <div @click="up"></div>
</template>

methods: {
    up() {
        this.$emit('upup','hehe'); //Actively trigger the upup method, 'hehe' is the data passed to the parent component
    }
}
Parent component:

<div>
    <child @upup="change" :msg="msg"></child> //Listen to the upup event triggered by the child component, and then call the change method
</div>
methods: {
    change(msg) {
        this.msg = msg;
    }
}

3. Non-parent-child component communication
If 2 components are not parent and child components then how to communicate? At this time, communication can be achieved through eventHub.
The so-called eventHub is to create an event center, which is equivalent to a transit station, which can be used to transmit and receive events.

let Hub = new Vue(); //Create event hub

Component 1 triggers:
<div @click="eve"></div>
methods: {
    eve() {
        Hub.$emit('change','hehe'); //Hub triggers an event
    }
}

Component 2 receives:
<div></div>
created() {
    Hub.$on('change', () => { //Hub receives events
        this.msg = 'hehe';
    });
}
In this way, the communication between non-parent and child components is realized. The principle is to use the Hub as a transit station!

  

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325260436&siteId=291194637