How does Vue implement communication between components?

How does Vue implement communication between components?

1. Communication between father and son

The most common communication is between father and son, which is a two-way data transmission.

1.1 Parent component --> Son component

The way a parent component passes data to its child component is to pass data to the child component through Prop.

//child.vue
<template>
    <div>
        I am the son, and I received the data from my father as {{value}}
    </div>
</template>

<script>
export default {
    props:{
        value: String
    }
}
//App.vue
<template>
  <div id="app">
    <Child :value="x" />
  </div>
</template>

<script>
import Child from './components/Child'
export default {
  data(){
    return {
      x: 'hi,child'
    }
  },
  components:{
    Child
  }
}
</script>

1.2 Son component --> parent component

The way the child component passes data to the parent component is to trigger a custom event through $emit in the child component. When the child component is used, v-on is bound to listen for the custom event.

The v-on event communication here is automatically listened to as the event attribute of the subcomponent when it is used by the subcomponent.

Therefore, the child component passes data to the parent component, depending on the custom event attributes used by the child component.

//child.vue
<template>
    <div>
        I am the son, and I received the data from my father as {{value}}
        <button @click="sayHi">
            Say hello to the parent component</button>
    </div>
</template>

<script>
export default {
    props:{
        value: String
    },
    methods:{
        sayHi(){
            this.$emit('sayHi','hi,parent!');
        }
    }
}
</script>
//App.vue
<template>
  <div id="app">
    I am the parent component, and the data I receive from the child component is {{y}}
    <Child :value="x" @sayHi="y = $event"/>
  </div>
</template>

<script>
import Child from './components/Child'
export default {
  data(){
    return {
      x: 'hi,child',
      y: ''
    }
  },
  components:{
    Child
  }
}
</script>

2. Communication between grandfather and grandson

For communication between grandfather and grandson, two v-on communications can be used, grandfather to father communication, and then father to son communication.

You can also use any of the following inter-component communication methods.

3. Communication between any components

The communication between any components no longer distinguishes whether it is A communicating with B or B communicating with A. Instead, it is a universal way. Whoever wants to send data uses the corresponding API to send data, and whoever wants to receive data uses the corresponding API to receive it.

There are two ways to communicate between any components. One is to use EventBus publish-subscribe mode communication, and the other is to use Vuex communication.

3.1 EventBus

EventBus, literally means event bus. All data transmitted by triggered events are saved on the bus from the front door, and then the corresponding event data is allowed to get off the bus by listening to the exit provided by the corresponding event.

EventBus actually means the publish and subscribe mode, that is, whoever wants to pass data out must publish the data through the API that triggers the custom event; whoever needs to receive the data information must monitor the data through the event monitoring API. Once the monitored data is detected to be published, it will be received. This is data subscription.

The most important thing about EventBus communication is to understand the publishing and subscription APIs. In Vue, the Vue instance provides two interfaces, $emit and $on , so you can create a new empty Vue instance to obtain these two interfaces.

const eventBus = new Vue();
eventBus.$emit(eventName, […args]) //Publish event eventBus.$on(event, callback) //Subscribe to event

The following are examples:

// eventBus.js
import Vue from 'vue'
export const eventBus = new Vue();
//child
<template>
    <div>
        I am the son and I received the data from my father as <strong>{{value}}</strong>
        <button @click="sayHi">
            Say hello to the parent component</button>
        <button @click="sibling">
            Say hello to sibling components</button>
    </div>
</template>

<script>
import {eventBus} from '../eventBus.js'
export default {
    props:{
        value: String
    },
    methods:{
        sayHi(){
            this.$emit('sayHi','hi,parent!');
        },
        sibling(){
            eventBus.$emit('sibling','hi,brother');
        }
    }
}
</script>

<style scoped>
    strong{
        color: red;
    }
</style>
//sibling
<template>
    <div>
        I am a brother component, and the data information I receive from the son component is <strong>{{x}}</strong> 
    </div>
</template>

<script>
import {eventBus} from '../eventBus.js'
export default {
    data(){
        return {
            x: ''
        }
    },
    mounted(){
        eventBus.$on('sibling', (msg)=>{
            this.x = msg;
        })
    }
}
</script>

<style scoped>
    strong{
            color: green;
    }
</style>
//parent
<template>
  <div id="app">
    I am the parent component, and the data I receive from the child component is <strong>{{y}}</strong>
    <Child :value="x" @sayHi="y = $event"/>
    <Sibling></Sibling>
  </div>
</template>

<script>
import Child from './components/Child'
import Sibling from './components/Sibling'
export default {
  data(){
    return {
      x: 'hi,child',
      y: ''
    }
  },
  components:{
    Child,
    Sibling
  }
}
</script>

<style scoped>
    strong{
            color: blue;
    }
</style>

Regarding EventBus, there may be a question: since there are $emit and $on in the Vue instance, why not just use this.$emit to trigger events and this.$on to receive events? You also have to have an extra empty instance eventBus = new Vue(). That's because each component in Vue is a separate Vue instance. If you trigger the emit event of this instance in this Vue instance, the on event of another instance cannot be received. How can event communication be carried out if you are not on the same bus? Therefore, a public bus is necessary, which is the event bus.

The usage of eventBus in the above example is local eventBus. Anyone who wants to use eventBus needs to introduce it manually. You can also make eventBus global, such as hanging it on the prototype of vue.

//main.js
import Vue from 'vue'
import App from './App.vue'

Vue.config.productionTip = false

Vue.prototype.$eventBus = new Vue(); //Add this sentence, it must be before the new Vue below.

new Vue({
  render: h => h(App),
}).$mount('#app')
//child
sibling(){
    this.$eventBus.$emit('sibling','hi,brother');
}
//sibling
mounted(){
    this.$eventBus.$on('sibling', (msg)=>{
        this.x = msg;
    })
}

In addition to the above method of adding properties to the Vue prototype, you can also use Object.defineProperty() to add properties to the Vue prototype.

import Vue from 'vue'
import App from './App.vue'

Vue.config.productionTip = false

let eventBus = new Vue()
Object.defineProperty(Vue.prototype,'$eventBus',{
  get(){
    return eventBus
  }
})

new Vue({
  render: h => h(App),
}).$mount('#app')

3.2 Vuex

Communication between Vue components can also use a state management mode developed specifically for vue.js applications: Vuex. The use of Vuex is relatively complicated, see the Vuex blog for details. Vuex is suitable for state management of large and complex Vue projects. For some small and medium-sized applications, you can customize the store mode according to the principle of Vuex for state management. For details on vue custom state management, see Vue Simple State Management - Store Mode Blog.

Whether it is Vuex or custom store mode, the principle of realizing communication between components is achieved by sharing data. Components use the same data source. When one component changes its data, the data source that another component depends on also changes.

The above is the details of how Vue implements communication between components. For more information about communication between Vue components, please pay attention to other related articles on 123WORDPRESS.COM!

You may also be interested in:
  • Details of 7 kinds of component communication in Vue3
  • Vue component communication method case summary
  • Eight examples of how Vue implements component communication
  • A very detailed summary of communication between Vue components
  • How to implement parent-child component communication with Vue
  • Eight ways of component communication in Vue (worth collecting!)
  • Six ways of communication between Vue components (summary)
  • Several implementation methods of Vue component communication
  • Summary of communication methods between Vue components (parent-child components, sibling components, and ancestor-descendant components)
  • Several ways for Vue to achieve communication between components (multiple scenarios)

<<:  How to analyze SQL execution plan in MySQL through EXPLAIN

>>:  Nginx rush purchase current limiting configuration implementation analysis

Recommend

Detailed explanation of importing/exporting MySQL data in Docker container

Preface We all know that the import and export of...

Seven Principles of a Skilled Designer (2): Color Usage

<br />Previous article: Seven Principles of ...

jQuery realizes the shuttle box function

This article example shares the specific code of ...

Detailed installation and configuration tutorial of PostgreSQL 11 under CentOS7

1. Official website address The official website ...

Introduction to generating Kubernetes certificates using OpenSSL

Kubernetes supports three types of authentication...

Is a design that complies with design specifications a good design?

In the past few years of my career, I have writte...

Record a troubleshooting record of high CPU usage of Tomcat process

This article mainly records a tomcat process, and...

jQuery canvas generates a poster with a QR code

This article shares the specific code for using j...

How to encapsulate axios request with vue

In fact, it is very simple to encapsulate axios i...

About the problem of offline installation of Docker package on CentOS 8.4

The virtual machine used is CentOS 8.4, which sim...

Two ways to implement HTML page click download file

1. Use the <a> tag to complete <a href=&...

Use the Linux seq command to generate a sequence of numbers (recommended)

The Linux seq command can generate lists of numbe...

...

How to set horizontal navigation structure in Html

This article shares with you two methods of setti...

Vue project realizes paging effect

The paging effect is implemented in the vue proje...