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

A brief discussion on MySQL select optimization solution

Table of contents Examples from real life Slow qu...

Detailed explanation of Linux one-line command to process batch files

Preface The best method may not be the one you ca...

Use of filter() array filter in JS

Table of contents 1. Introduction 2. Introduction...

How to write a MySQL backup script

Preface: The importance of database backup is sel...

Detailed explanation of this reference and custom properties in JavaScript

Table of contents 1. this keyword 2. Custom attri...

Deleting two images with the same id in docker

When I created a Docker container today, I accide...

Native JS to achieve image marquee effects

Today I will share with you a picture marquee eff...

How to set directory whitelist and IP whitelist in nginx

1. Set a directory whitelist: Do not set restrict...

js dynamically generates tables (node ​​operations)

This article example shares the specific code of ...

MySQL 8.0.12 decompression version installation tutorial personal test!

Mysql8.0.12 decompression version installation me...

Solution to the failure of docker windows10 shared directory mounting

cause When executing the docker script, an error ...

Detailed explanation of linux crm deployment code

Linux basic configuration Compile and install pyt...

Differences in the hr separator between browsers

When making a web page, you sometimes use a dividi...

Detailed explanation of the usage of the alias command under Linux

1. Use of alias The alias command is used to set ...