Vue component communication method case summary

Vue component communication method case summary

1. Parent component passes value to child component (props)

step:

  1. Pass data to child components through v-bind in the parent component
  2. Receive data passed from the parent component through props in the child component
<div id="app">
	<!-- 1. Pass data to child components through v-bind -->
    <test v-bind:ss='name'></test>
</div>

<script>
    var a = new Vue({
        el:'#app',
        data:{
            name:'bing',
        },
        components:
            test:{
                props: ['ss'], // 2. Receive data passed by the parent component template: "<p>{{ss}}</p>"
            }
        }
    })
</script>

Props creates a單向數據流between parent and child elements. When the parent element is updated, the state of the child element will also change accordingly.
But the opposite will make the data flow of your application difficult to understand, so the data in the parent component cannot be modified in the child component .

2. Subcomponents pass values ​​to parent components ($emit)

The child component sends a message to the parent component through the $emit event and passes its own data to the parent component.

step:

  1. Bind a click event to the child component to trigger increment method
  2. In the increment method, use $emit to define a custom event increment and pass in the this.counter parameter
  3. Bind the custom increment event in step 2 to the parent component, the method name is incrementTotal
  4. Call the incrementTotal method in step 3 in the parent component. Then incrementTotal method can receive the parameters passed in by the child component.
<div id="app">
    <p>{{ total }}</p>
    <button-counter v-on:increment="incrementTotal"></button-counter> <!-- Step 3 -->
</div>

<script>
    Vue.component('button-counter', {
        template: '<button v-on:click="increment">{{ counter }}</button>', // Step 1
        data: function () {
            return {
                counter: 'Subcomponent data'
            } 
        },
        methods: {
            increment: function () {
                this.$emit('increment', this.counter); // Step 2
            }
        }
    });


    new Vue({
        el: '#app',
        data: {
            total: 'Parent component data:'
        },
        methods: {
            incrementTotal: function (e) { // Step 4
                this.total = this.total + e[0]
                console.log(e);
            }
        }
    })
</script>

3. Brother component value transmission (EventBus)

If you don't need a library like Vuex to handle data communication between components, you can consider using the EventBus in Vue to communicate.

In Vue, EventBus can be used as a communication bridge, just like all components share the same event center, and can register to send or receive events from the center, so components can notify other components in parallel.
But it is too convenient, so if used carelessly, it will cause a "disaster" that is difficult to maintain. Therefore, a more complete Vuex is needed as the state management center to elevate the concept of notification to the shared state level.

This method is to create an empty vue instance as the processing center (event bus) of the $emit event, through which to trigger and listen to events, and conveniently realize the communication between any components, including parent-child, sibling, and inter-generation components. The details are as follows:

1. Initialization (new Vue())

First you need to create the event bus and export it so that other modules can use or listen to it.
We can handle this in two ways.

Method 1: Create a new event-bus.js file

// event-bus.js
import Vue from 'vue'
export const EventBus = new Vue()

Method 2: Initialize EventBus directly in main.js of the project

// main.js
Vue.prototype.$EventBus = new Vue() // Note: EventBus initialized in this way is a global event bus

Now that we have created EventBus , all you need to do is load it in your component and call the same method as you did to pass messages between parent and child components.

2. Sending events ($emit())

Suppose there are two Vue pages that need to communicate: A and B. In page A, a click event is bound to the button and a message is sent to notify page B.

<!-- A.vue -->
<template>
    <button @click="sendMsg()">-</button>
</template>

<script> 
import { EventBus } from "../event-bus.js";
export default {
  methods: {
    sendMsg() {
      EventBus.$emit("aMsg", 'Message from page A'); // Send data externally}
  }
}; 
</script>

3. Receive events ($on())

Next, you need to receive this message in page B.

<!-- B.vue -->
<template>
	<p>{{msg}}</p>
</template>

<script> 
import { EventBus } from "../event-bus.js";
export default {
	data() {
		return {
			msg: ''
		}
	},
	mounted() {
		EventBus.$on("aMsg", (msg) => { // Receive the message sent by A this.msg = msg;
		});
	}
};
</script>

4. Remove event listeners

As mentioned before, if used improperly, EventBus can be a disaster. What kind of “disaster” is it? Everyone knows that vue is a single-page application. If you refresh a page, the related EventBus will be removed, which will cause the business to stop. Also, if the business has pages that are repeatedly operated, EventBus will be triggered many times when monitoring, which is also a very big hidden danger. At this time, we need to properly handle the relationship between EventBus and the project. It is usually used to remove EventBus event listeners when the vue page is destroyed.

If you want to remove the event listener, you can do it like this:

import { EventBus } from "../event-bus.js";
EventBus.$off('aMsg', {})

EventBus.$off('aMsg') removes all listeners for this event in the application.
Or you can directly call EventBus.$off() to remove all event channels without adding any parameters.

4. Vuex

When making medium-to-large single-page applications, such as those that require collaborative development by multiple people and global maintenance of login status, it is best to choose vuex for state management.

Vuex detailed explanation portal

This is the end of this article about the case summary of Vue component communication methods. For more relevant Vue component communication method summaries, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Detailed explanation of seven component communication methods of Vue3
  • Three Vue slots to solve parent-child component communication
  • Details of 7 kinds of component communication in Vue3
  • Eight examples of how Vue implements component communication
  • Detailed explanation of component communication in Vue (father-child component, grandfather-grandson component, brother component)
  • Several ways of communication between Vue components

<<:  Detailed steps for configuring Tomcat server in IDEA 2020

>>:  Detailed explanation of MySQL partition table

Recommend

Super detailed teaching on how to upgrade the version of MySQL

Table of contents 1. Introduction 2. Back up the ...

Implementation of vue+drf+third-party sliding verification code access

Table of contents 1. Background 2. Verification p...

js drag and drop table to realize content calculation

This article example shares the specific code of ...

MySQL SQL statement to find duplicate data based on one or more fields

SQL finds all duplicate records in a table 1. The...

jQuery combined with CSS to achieve the return to top function

CSS Operations CSS $("").css(name|pro|[...

Detailed explanation of the use of Join in Mysql

In the previous chapters, we have learned how to ...

Detailed explanation of several ways to install CMake on Ubuntu

apt install CMake sudo apt install cmake This met...

How to install Element UI and use vector graphics in vue3.0

Here we only focus on the installation and use of...

How to design and optimize MySQL indexes

Table of contents What is an index? Leftmost pref...

How to install WSL2 Ubuntu20.04 on Windows 10 and set up the docker environment

Enable WSL Make sure the system is Windows 10 200...

Some conclusions on developing mobile websites

The mobile version of the website should at least...

Detailed description of the life cycle of React components

Table of contents 1. What is the life cycle 2. Lo...

Issues and precautions about setting maxPostSize for Tomcat

1. Why set maxPostSize? The tomcat container has ...