vue3 eventBus subscription publishing mode

Ⅰ. What is eventBus?

In layman's terms, in any component, you want to pass the message (parameter) -> to any component and execute certain logic.

Ⅱ. How vue3 uses eventBus

  • There is no eventBus in vue3, so we have to write it ourselves, but it is very simple.

Step 1 (eventBus container)

  • In the src directory, create a bus folder to store the bus.js written by yourself;
  • Write bus.js => bind three (subscribe, unsubscribe, publish) functions to the class prototype;
// bus.js
class Bus {
    
    
	constructor() {
    
    
		this.list = {
    
    };  // 收集订阅
	}
	// 订阅
	$on(name, fn) {
    
    
		this.list[name] = this.list[name] || [];
		this.list[name].push(fn);
	}
	// 发布
	$emit(name, data) {
    
    
		if (this.list[name]) {
    
    
      		this.list[name].forEach((fn) => {
    
    	fn(data);   });
    	}
	}
	// 取消订阅
	$off(name) {
    
    
		if (this.list[name]) {
    
    
			delete this.list[name];
		}
	}
}
export default new Bus;
  • Subscriber (on), put the function into the list => wait for the publisher (emit), pass parameters to call;
  • Since the function is an object, the memory address has not changed and is still executed in the subscriber (on) component.

Step 2 (Subscribers)

  • Subscribe in comA.vue;
  • Subscriptions only store functions and do not execute them until they are published;
<template>
  <div>
 	{
   
   { name }} --- {
   
   { age }}
  </div>
</template>
<script>
import {
     
     ref , onUnmounted} from 'vue';
import Bus from '../bus/bus.js';
export default {
     
     
  setup() {
     
     
       const name = '张三';
       const age = ref(18)
       Bus.$on('addAge',({
     
      num })=>{
     
         age.value = num;    })
       
       //组件卸载时,取消订阅
	   onUnmounted( () => {
     
      Bus.$off('addAge') } )
 	}
 }
</script>
  • When leaving the component (onUnmounted), delete the array of registered and subscribed functions to avoid storing more and more.

Step 3 (Publisher)

  • Publish in comB.vue;
  • Call subscription and pass parameters;
<template>
    <button @click="fabu">发布</button>
</template>
<script>
import Bus from '../bus/bus.js';
export default {
     
     
  setup() {
     
     
	 function fabu(){
     
     
 		Bus.$emit('addAge',{
     
     age:'19'});
	 }
   }
 }
</script>
  • After publishing, the component of the subscriber will be executed. Note that the name of the corresponding subscription and publication should be the same.

Guess you like

Origin blog.csdn.net/weixin_42232622/article/details/126589557