The principle and exploration process of global event bus in Vue

Keywords: Javascript Front-end Vue.js

preface

In the previous article, I wrote about custom events in Vue. Custom events are the basis of the global event bus. I buried a small foreshadowing in my last article. As shown below:

As I said, in Vue, if we use (@ ORV on) to bind a custom event to the component, its essence is to bind an event to the child component VueComponent, that is, vc. Then the child component is triggered through this.$emit(), and the parent component listens to it and then executes the callback method. This is only suitable for communication between parent and child components, but it is still not very convenient for brother components.

What is the global event bus like?

1, Global event bus

Provide a thinking direction:

The same is true for other components.

At this stage, we need to understand one thing. The word "global event bus" means that it can be accessed globally. And be able to bind methods?

That is, $on, $off and $emit are guaranteed in xxxx to realize the communication between components.

So where is it??

When we bound a custom event to a child component before, its essence is not to bind a custom event to the instance object new VueComponent of the child component.

In this global event bus, we can no longer bind custom events to the instance object of each component, but bind custom events to an object that can be accessed by all components.

So that object can be accessed by everyone? Look at the picture below.

---Figure: from Shangsi Valley - Mr. Zhang Tianyu

We put it on the vue prototype, then the global event bus can achieve the communication between any component.

2, Installing the global event bus

When we find out who to look for, we must define it, otherwise how to use it.

The standard is defined as follows:

import Vue from 'vue'
import App from './App.vue'

Vue.config.productionTip = false

// Instructions for global bus
// When using the global bus, the better application is between brother components and grandson components. These components cannot communicate directly. It will be much more convenient to use the global event bus
new Vue({
  render: h => h(App),
  // beforeCreate the lifecycle function before the data is mounted
  beforeCreate () {
    // Installing the global event bus $bus is the vm of the current application, and this here is the current new Vue()
    Vue.prototype.$bus = this
  }
}).$mount('#app')

beforCreate() method

It is the first of many life cycles. At this point, its this is the current vue

3, Use global event bus

1. Receive data: if component a wants to receive data, bind a custom event to $bus in component A, and the callback of the event remains in component a itself. This is the first step in the illustration.

// Press enter to add a todo
addTodo (todo) {
    this.todos.unshift(todo)
},
    // Judge whether it is checked or not
    checkTodo (id) {
        this.todos.forEach((todo) => {
            if (todo.id === id) todo.done = !todo.done
        })
    },
        // Delete a todo
        deleteTodo (id) {
            this.todos = this.todos.filter(todo => todo.id !== id)
        },
            // Select all or none
            checkAllTodos (done) {
                this.todos.forEach((todo) => { todo.done = done })
            },
                // Clear all completed tasks
                clearDoneTodos () {
                    this.todos = this.todos.filter(todo => !todo.done)
                }
},
    // Bind the global bus after loading
    mounted () {
        this.$bus.$on('addTodo', this.addTodo)
        this.$bus.$on('checkTodo', this.checkTodo)
        this.$bus.$on('deleteTodo', this.deleteTodo)
    },

2. Data provided: this.$bus.$emit('xxxx ', data)

  methods: {
    add () {
      // 1. Check the validity of input
      const title = this.title.trim()
      if (!title) {
        alert('Please enter the content')
        return
      }
      const id = uuidv4()
      // 2. Generate a todo object according to the input
      const todo = { id, title, done: false }
      // 3. Add to todos
      this.$bus.$emit('addTodo', todo)
      // 4. Clear input
      this.title = ''
    }
  }
}

Note: finally, in the beforedestination hook, use $off to unbind the events used by the current component.

As shown below:

There are many ways to unbind, $off() does not write parameters, but unbinds all directly

A parameter $off('xxx ') is to unbind one. Unbinding multiple parameters can be written as $off ('xx', 'xxx']

Post language

Let's cheer together!!! If there are any deficiencies in the article, please point out them in time. Thank you very much.

I feel shallow on paper. I absolutely know that I have to practice it.

Hello, I'm blogger Ning Zaichun: homepage

A young man who likes literature and art but embarks on the road of programming.

Hope: when we meet on another day, we have achieved something.

Posted by trixiesirisheyes on Sat, 20 Nov 2021 13:30:34 -0800