search
HomeWeb Front-endJS TutorialDetailed interpretation of eventbus in vue

This article mainly introduces the pitfalls that eventbus has been triggered many times in vue and has been stepped on. The editor thinks it is quite good. Now I will share it with you and give you a reference. Let’s follow the editor and take a look.

The initial demand is like this. In order to realize data transfer between two page components, suppose I have page A and click a button on page A. After that, the page will automatically jump to page B. At the same time, I hope to carry some parameters on page A to page B. (I know that for small parameters, you can pass parameters through route params or query, or large data can be processed with vuex. Unfortunately, I haven’t done a very large project yet, so I haven’t used vuex yet. Next I will learn it.)

Then I thought, isn’t this just a problem of data transfer between different components? Wouldn't it be enough to directly use the bus event to transfer data? So, I went ahead happily. Regarding the use of eventbus in Vue, I mentioned it before in an article about data transfer in Vue.

Let me show you my initial code first:

Achieve the goal:

After clicking, the bus emit event will then jump to the /moneyRecord page.

The next step is to receive this event on the MoneyRecord page, and then accept the parameters.

// 这是页面A的内部触发bus事件的代码
 editList (index, date, item) {
// 点击进入编辑的页面,需要传递的参数比较多。
  console.log(index, date, item)
  bus.$emit('get', {
  item: item.type,
  date: date
  })
  this.$router.replace({path: '/moneyRecord'})
 }

// moneyRecord页面
created () {
 //这里我将icon的list给保存下来了
 bus.$on('get', this.myhandle)
 },
methods: {
 myhandle (val) {
  console.log(val, '这是从上个页面传递过来的参数')
 }
}

When I was ecstatic, I felt that as long as I triggered the get event on page A, page B would accept the data as a matter of course. However, the result was not satisfactory, take a look at the animation below.

Mainly depends on the number of output times of the row of data ""This is the data transmitted from the previous page" to determine the number of event triggers. ""

I don’t know if you have noticed, but when I first entered the list page, I clicked on any item under the list, and there was no output on the console. . But when I click to trigger the event for the second time, a test data will be output. Click in again and two data will be output. . . Increased in sequence. (The "This is the data transmitted from the previous page" on the console is the test data)

So, there are two questions.

Question:

  1. Question 1: Why is the on event in page B not triggered when it is triggered for the first time

  2. Question 2: Why does it appear when I trigger it again in sequence? Every time, I find that the previous on event distribution has not been revoked, causing more and more event triggers to be executed each time.

Solution

For problem 1

This has to start with the life cycle of vue, I will do it first Testing is when you jump from page component A to page component B, what are the life cycles of the two components? I won’t go into details about what Vue’s life cycle does in each period. I will post below. A diagram of the vue life cycle.

#I did my own experiments to verify the execution of the life cycles of these two components during the page jump process.

// 我分别在页面A和页面B中去添加以下代码:
beforeCreate () {
 console.group('%c%s', 'color:red', 'beforeCreate 创建前状态===============组件2》')
 },
 created () {
 console.group('%c%s', 'color:red', 'created 创建完毕状态===============组件2》')
 },
 beforeMount () {
 console.group('%c%s', 'color:red', 'beforeMount 挂载前状态===============组件2》')
 },
 mounted () {
 console.group('%c%s', 'color:red', 'mounted 挂载状态===============组件2》')
 },
 beforeUpdate () {
 console.group('%c%s', 'color:red', 'beforeUpdate 更新前状态===============组件2》')
 },
 updated () {
 console.group('%c%s', 'color:red', 'updated 更新状态===============组件2》')
 },
 beforeDestroy () {
 console.group('%c%s', 'color:red', 'beforeDestroy 破前状态===============组件2》')
 },
 destroyed () {
 console.group('%c%s', 'color:red', 'destroyed 破坏状态===============组件2》')
 }
// 另外一个组件的我就不放出来了

Test result picture:

In fact, you can clearly see through the results that when we are still on page A At the time, page B has not yet been generated, that is, the event from A monitored by created in page B has not yet been triggered. At this time, when you emit the event in A, B actually did not monitor it.

Look again, the red one is the B page component. What happens when you jump from page A to page B? First, the B component is created first, then beforeMount, and then the A component is destroyed, and then the A component executes beforeDestory and destoryed.

So, we can write the emit event in the A page component in beforeDestory. Because at this time, the B page component has been created, that is, the $on event we wrote has been triggered

So it is ok, during beforeDestory, the $emit event.

// 修改一下A页面中的代码:
// 这是原先的代码
 editList (index, date, item) {
// 点击进入编辑的页面,需要传递的参数比较多。
  console.log(index, date, item)
  this.item = item.type
  this.date = date
  this.$router.replace({path: '/moneyRecord'})
 }
// 重新在data属性内部定义新的变量,来存储要传过去的数据;
然后:
 beforeDestroy () {
 console.log(this.highlight, '这是今年的数据', this, '看看组件销毁之前会发生什么')
 bus.$emit('get', {
  item: this.item,
  date: this.date
  })
 },

Next. Take a look at the effect after the modification

You can see that when the list is clicked for the first time, that is, when the emit event is triggered for the first time, the control is output. , so going to $emit beforeDestoryed plays a role, and the B page component also monitors the arrival of $on.

However, it seems that the triggering of events will still increase in sequence, that is, the output of the console will increase each time. . .

Solution:

Look at what was proposed on github. https://github.com/vuejs/vue/issues/3399

You Dada proposed the following solution:

*就是说,这个$on事件是不会自动清楚销毁的,需要我们手动来销毁。(不过我不太清楚这里的external bus 是什么意思,有大神能解答一下的吗,尤大大也提到如果是注册的是external bus 的时候需要清除)****

所以。我在B组件页面中添加Bus.$off来关闭。代码如下:

// 在B组件页面中添加以下语句,在组件beforeDestory的时候销毁。
 beforeDestroy () {
 bus.$off('get', this.myhandle)
 },

来看一下输出的结果

t可以看到,控制台第一次进去的时候就有输出,而且输出的不会逐次增加

*当然,尤大大还说可以写一个mixin?我还不知道是什么?以后在研究一下。

总结: 所以,如果想要用bus 来进行页面组件之间的数据传递,需要注意亮点,组件A$emit事件应在beforeDestory生命周期内。其次,组件B内的$on记得要销毁。

提问时间:你们在实现页面组件之间的数据传递有什么好的方法吗?可以留言分享一下吗?有时候虽然也可以通过从后台获取,但是考虑到数据只有几个需要传的话,就没有必要去请求数据,我知道有的还有用vueX传递。还有呢?

上面是我整理给大家的,希望今后会对大家有帮助。

相关文章:

使用EasyUI如何绑定Json数据源

在vue-cli中如何实现组件通信

Vue项目优化需要注意哪些?

在vuejs中使用模块化的方式开发

The above is the detailed content of Detailed interpretation of eventbus in vue. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Atom editor mac version download

Atom editor mac version download

The most popular open source editor