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

JavaScript Basics: Error Capture Mechanism

Table of contents Preface Error Object throw try…...

Implementation of VUE infinite level tree data structure display

Table of contents Component recursive call Using ...

SQL Optimization Tutorial: IN and RANGE Queries

Preface "High Performance MySQL" mentio...

5 things to note when writing React components using hooks

Table of contents 01. Use useState when render is...

How to use VUE to call Ali Iconfont library online

Preface Many years ago, I was a newbie on the ser...

Web design reference firefox default style

Although W3C has established some standards for HT...

How to make if judgment in js as smooth as silk

Table of contents Preface Code Implementation Ide...

MYSQL transaction tutorial Yii2.0 merchant withdrawal function

Preface I am a PHP programmer who started out as ...

Several scenarios for using the Nginx Rewrite module

Application scenario 1: Domain name-based redirec...

How to install MySQL for beginners (proven effective)

1. Software Download MySQL download and installat...

MySQL 5.6.33 installation and configuration tutorial under Linux

This tutorial shares the installation and configu...