Detailed explanation of Vue's self-implementation of dispatch and broadcast (dispatch and broadcast)

Detailed explanation of Vue's self-implementation of dispatch and broadcast (dispatch and broadcast)

Problem to be solved

Mainly for cross-level communication between components

Why do you need to implement dispatch and broadcast yourself?

Because when developing independent components or libraries, it is best not to rely on third-party libraries

Why not use provide and inject?

Because its usage scenario is mainly for sub-components to obtain the status of parent components, an active provision and dependency injection relationship is established between cross-level components.
Then there are two scenarios that it cannot solve well:
The parent component passes data to the child component (supports cross-level);
The child component passes data to the parent component (supports cross-level).

The code is as follows:

emitter.js

function broadcast(componentName, eventName, params) {
 this.$children.forEach(child => {
  const name = child.$options.name;

  if (name === componentName) {
   child.$emit.apply(child, [eventName].concat(params));
  } else {
   // todo If params is an empty array, it will receive undefined
   broadcast.apply(child, [componentName, eventName].concat([params]));
  }
 });
}
export default {
 methods: {
  dispatch(componentName, eventName, params) {
   let parent = this.$parent || this.$root;
   let name = parent.$options.name;

   while (parent && (!name || name !== componentName)) {
    parent = parent.$parent;

    if (parent) {
     name = parent.$options.name;
    }
   }
   if (parent) {
    parent.$emit.apply(parent, [eventName].concat(params));
   }
  },
  broadcast(componentName, eventName, params) {
   broadcast.call(this, componentName, eventName, params);
  }
 }
};

parent.vue

<template>
 <div>
  <h1>I am the parent component</h1>
  <button @click="handleClick">Trigger event</button> <child />
 </div>
</template>
<script>
import Emitter from "@/mixins/emitter.js";
import Child from "./child";
export default {
 name: "componentA",
 mixins: [Emitter],
 created() {
  this.$on("child-to-p", this.handleChild);
 },
 methods: {
  handleClick() {
   this.broadcast("componentB", "on-message", "Hello Vue.js");
  },
  handleChild(val) {
   alert(val);
  }
 },
 components:
  Child
 }
};
</script>

child.vue

<template>
 <div>I am a child component</div>
</template>
<script>
import Emitter from "@/mixins/emitter.js";
export default {
 name: "componentB",
 mixins: [Emitter],
 created() {
  this.$on("on-message", this.showMessage);
  this.dispatch("componentA", "child-to-p", "hello parent");
 },
 methods: {
  showMessage(text) {
   window.alert(text);
  }
 }
};
</script>

In this way, cross-level component custom communication can be achieved. However, one problem should be noted: subscription must precede publishing, that is, on must come before emit.

Parent-child component rendering order, instance creation order

The child component is rendered before the parent component, so when the mounted event of the child component is dispatched, it cannot be heard in the mount in the parent component.
The create of the parent component precedes the child component, so the create in the parent component can be monitored

This is the end of this article about Vue's self-implemented dispatch and broadcast (dispatch and broadcast). For more relevant Vue dispatch and broadcast content, please search 123WORDPRESS.COM's previous articles or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Vue SPA single-page application first screen optimization practice
  • Vue implementation example of boradcast and dispatch
  • vue-cli single page pre-rendering seo-prerender-spa-plugin operation
  • Usage of store.commit and store.dispatch in vuex
  • Vue SPA first enters the loading animation implementation code
  • Vue realizes the effect of merging columns in data table rowspan
  • Routing caching problems and solutions in Vue SPA applications
  • Solve the problem that Vuex's Dispatch has no effect under Vue+Electron
  • VUE solves the WeChat signature and SPA WeChat invalid signature problem (perfect processing)
  • Detailed explanation of when the action in vuex is completed and how to call dispatch correctly
  • Vue SPA first screen optimization solution

<<:  How to change the root password in MySQL 5.7

>>:  How to implement remote automatic backup of MongoDB in Linux

Recommend

Tutorial on installing Microsoft TrueType fonts on Ubuntu-based distributions

If you open some Microsoft documents with LibreOf...

MySQL derived table (Derived Table) simple usage example analysis

This article uses an example to describe the simp...

How to implement communication between Docker containers

Scenario: A laradock development environment (php...

Introduction and use of triggers and cursors in MySQL

Trigger Introduction A trigger is a special store...

Detailed explanation of the TARGET attribute of the HTML hyperlink tag A

The hyperlink <a> tag represents a link poin...

JavaScript to implement the countdown for sending SMS

This article shares the specific code of JavaScri...

Tutorial on deploying jdk and tomcat on centos7 without interface

1. Install xshell6 2. Create a server connection ...

How to use ECharts in WeChat Mini Programs using uniapp

Today, we use uniapp to integrate Echarts to disp...

Node.js returns different data according to different request paths.

Table of contents 1. Learn to return different da...

How to use CSS to achieve data hotspot effect

The effect is as follows: analyze 1. Here you can...

Detailed explanation of how to use the Vue date time picker component

This article example shares the specific code of ...

vue+rem custom carousel effect

The implementation of custom carousel chart using...

Solution to the MySQL error "Every derived table must have its own alias"

MySQL reports an error when executing multi-table...

HTML table tag tutorial (21): row border color attribute BORDERCOLOR

To beautify the table, you can set different bord...

MySQL 5.7 installation and configuration tutorial

This article shares the MySQL installation and co...