If you need to use peer component communication in multiple places in your project, but don’t want to write a tedious VUEX, this is a good idea. I am writing in the project to figure out, feel very good to use, share.
1. Add busEvent.js to the utils folder
The comments are already very detailed and very simple, so I don’t want to elaborate too much.
import Vue from "vue";
const Bus = new Vue();
/** * Commit event * @param {String} Component Name of the target component to submit * @param {String} Action Name of the target component to call * @param {any} param method parameter of the target component */
export const BusEmit = (component, action, param) = > {
Bus.$emit(component, action, param);
};
/** * peer component communication, listen for destruction events */
export const BusOn = {
mounted() {
Bus.$on(`The ${this.$options.name}`.this.onBusAction);
},
beforeDestroy() {
Bus.$off(`The ${this.$options.name}`.this.onBusAction);
},
methods: {
onBusAction(action, param) {
log('Calling component:The ${this.$options.name}Methods:${action}And parameters:${param}`);
this[action](param); }}};Copy the code
2. Components that need to listen for events
Introduce busons to mount on component mixins.
import { BusOn} from "@/utils/BusEvent";
export default {
name: "app".mixins: [BusOn],
methods: {
show(is){
console.log(is); }}Copy the code
3. Components that initiate communication
Introduce BusEmit to initiate peer component communication.
import { BusEmit} from "@/utils/BusEvent";
export default {
name: "child".methods: {
emitShow(is){
I'm going to call the app component's show method with a true argument
BusEmit("app"."show".true)}}Copy the code
Benefits:
- It is tedious not to import Bus in each component and then listen on mounted beforeDestroy (eventbus listening events must be destroyed).
- It provides good extensions, which components you want to call, which methods you want to call, and which parameters you want to pass.
- You can import and call component methods in other JS files.
For example: htttp.js
Some code is omitted and a function to handle error messages is defined.
import { BusEmit } from ".. /utils/event-bus"; ** @param {Number} status Status code of a failed request */ const errorHandle = err => {//.... Omit BusEmit ("app"."toast",{
text:'Failed to connect to server',
time:1000,
})
}
Copy the code
Of course you can do more encapsulation in busEvent.js, or if you have a better idea, please share with us.