1. Communication between components

  1. Father and son components:
    1. usepropsandemit()To communicate through events
    2. throughthis.$refsor$the parent and childrenGet parent-child element mode communication
    3. Child components through the Settings slot<slot name=''></slot>Parent to child communication
  2. Ye sun components:
    1. Use twicepropsandemit(), through the communication between grandpa and dad, father and son to achieve parent-grandson communication
    2. $attrand$listeners
  3. Any component:
    1. useeventBus = new Vue()To communication,eventBus.$oneventBus.$emitIs the main API
    2. useVuexcommunication

2. Father-son correspondence

2.1propsandemit()

2.1.1 Parent to Child: The father binds attributes to the son, and the son receives attributes through props
/ / the parent component<Child :name="father" :f_data="message"/>
Copy the code
/ / child component
props: ['name'.'f_data']
Copy the code
// Subcomponent 2
props: {name: {type:String.default: 'father',},f_data: {type: String|Number.validator(){}}}Copy the code
2.1.2 Child to Parent: The child component calls the v-on binding method of the parent component on the child component through emit() and communicates with the method by passing arguments
/ / the parent component<Child v-on:handle='changeMsg'></Child>
Copy the code
// The child passes value data to the parent<button @click="$emit('handle',value)"></button>
Copy the code

2.2 this.$refsor$the parent and childrenBoth are vUE instances that get the father or son

/ / child component
<template>
    <button>click me </button>
</template>
<script>
    export default {
        data(){
        return{
            sonMessage:'Message from the Son'
       },
        mounted(){
        console.log(this.$parent.$el.innerHTML);
        / / < div > < button > click me < / button > < / div > < / p > < p > father components}}</script>
Copy the code
/ / the parent component
<template>
<div>
 <child ref='childRef'>click me </child>
 <p>Dad components</p>
</div>
</template>

<script>
    export default {
        data(){
            return{
            fatherMessage:'Father's Message'}}},mounted(){
        console.log(this.$refs.childRef.sonMessage); // Son's information
        console.log(this.$children[0].sonMessage); // Son's information
        }
</script>
Copy the code

2.3 <slot></slot>

The parent component

<div>
    <Child>This is the default<template v-slot:name>Zhang SAN</template>
    <Child>
    
</div>
Copy the code

Child components

<div>
    <slot></slot>  <! -- This is the default -->
    <slot name='title'></slot> <! - zhang -- -- >
</div>
Copy the code

3. Parent-grandson correspondence

3.1 Use twicepropsandemit()

Grandpa components

<template>
    <parent name='zhanshan' @onParentClick="sendMessage" ></parent>
</template>

<script>
import Vue from 'vue'
import Parent from './parent.vue'
Vue.component('parent', Parent);
export default {
    methods: {
    sendMessage(sonMsg){
        console.log(sonMsg)   // Message from sun Tzu}}}</script>
Copy the code

Father components

<template>
    <child :name='name' @onChildClick="$emit('onParentClick',arguments[0])" ></child>
</template>

<script>
import Vue from 'vue'
import Child from './child'
Vue.component('child', Child);
export default {
    props: ['name']}</script>
Copy the code

The grandson components

<template>
    <button @click=$emit('onChildClick',' message from Sun Tzu ')" >click me </button>
</template>
<script>
export default {
    props: ['name']   //'zhangshan'
}
</script>
Copy the code

The grandfather sets the name attribute to the father, and the father receives and sets it again, so that the son receives the information from the grandfather. The son calls the method passed from grandpa to his father through emit() and passes parameters to grandpa to complete the communication

3.2 the use of$attrand$listenersSimplify step 3.1 above

The main code to use $attr

/ / grandpa
<Parent name="zhangshan"/>

/ / father
<Child v-bind="$attrs"/>

// Grandson props props
<div>{{name}}</div>
props:['name']

Copy the code
// Grandson props does not accept
<div>{{$attrs.name}}</div>
Copy the code

Use $Listeners’ main code

/ / grandpa
<parent @onChildClick="sendMessage" ></parent>

methods: {
    sendMessage(sonMsg){
        console.log(sonMsg)   // Message from sun Tzu
        }
/ / father
<child v-on="$listeners" ></child>

/ / a grandson
<button @click=$emit('onChildClick',' message from Sun Tzu ')" >click me </button>
Copy the code

4. Communicate with any component

4.1 Declare a global Vue instance variableEventBus, upload the data that needs to be communicated to this variable, which can realize the communication of various components. The equivalent of a component subscribing to eventBus is that one component passes information to eventBus, and eventBus publishes that information to all the other components that subscribe to it

Sibling communication Example

/ / the parent component
data(){
        return{
            eventBus:new Vue()
        }
    },
provide(){  // Provide an event center so that all descendant components can be used in eventBus, or imported as JS with import
    return{
        eventBus:this.eventBus
          }
        },
mounted(){
    this.eventBus.$on('click'.(a_message) = >{  // Listen for eventBus information
        console.log(a_message);   / / childB information
    })

Copy the code
/ / ChildA components
<template>
<div>
    <button @click='onClickFun'>ChildA button</button>
</div>
</template>
<script>
export default {
    inject: ['eventBus'].// Receive event center
    data(){
        return{
            a_message:'Information for childB'}},methods: {
        onClickFun(){// Click the button to send the a_message message to eventBus
            this.eventBus.$emit('click'.this.a_message)
        }
    }
</script>
Copy the code
/ / ChildB components
inject: ['eventBus'].// Receive event center
mounted(){
    this.eventBus.$on('click'.(a_message) = >{  // Listen for eventBus information
        console.log(a_message);   / / childB information
    })

Copy the code

4.2 Vuex

Vuex is a state management mode developed specifically for vue.js applications. It uses centralized storage to manage the state of all components of an application and rules to ensure that the state changes in a predictable way.

Accessing state data
//store.js
import Vue from "vue";
import Vuex from "vuex";

Vue.use(Vuex);

export default new Vuex.Store({
// Customize the share status
    state: {
        isMsg: true}});Copy the code
//main.js
import store from "./store";

new Vue({
  store,   // Mount store to Vue instance
  render: h= > h(App)
}).$mount("#app");
Copy the code
<! --App.vue-->
<div id='app'>{{$store.state.isMsg}}</div>   <! --true-->
Copy the code
Modify data by mutation
<! --App.vue--><button @click = 'onClick'>Example Modify isMsg in VueX</button>

methods:{
    onClick(){
      this.$store.commit('onChangeMsg'.false) // the first parameter is the mutation name}},Copy the code
//store.js
export default new Vuex.Store({
    state: {
        isMsg: true
    },
    mutations: {    // The only way to modify data, focus on modifying data for years
        onChangeMsg(state, data) {
            state.isMsg = data;
            console.log('Modify data'); }},Copy the code
Send asynchronous requests through actions
//app.vue
<button @click='onDispatch'> Send asynchronous requests through actions </button><span>OuterData:{{$store.state.outerData}}</span> // Asynchronously requested data
 methods:{
    onDispatch(){
      this.$store.dispatch("getOuterData")}Copy the code
//store.js
export default new Vuex.Store({
        state: { 
        outerData: ' '       // The data obtained by the asynchronous request is stored in state, and the next request is fetched directly from state
    },
    mutations: {
        onGetOuterData(state, data){ state.outerData = data; }},actions: {
        getOuterData(state) {
            axios({
                url: 'xxxx'.// Request the address of the data
                headers: {}
            }).then((res) = > {
                state.commit('onGetOuterData',res.data)
            })
        }
    },
});
Copy the code

Summary: According to the official flow chart, VueX will modify data in the order of requesting asynchronous data using Actions through Dispatch method, submitting data to Mutations through Commit method, and adding or modifying data to State through Commit method