


How to solve the problem of eventbus being triggered multiple times in Vue
The initial requirement is like this. In order to realize data transfer between two page components, suppose I have page A. After clicking a button on page A, the page will automatically jump to Page B, and I want to carry some parameters on page A to page B. (For small parameters, you can pass parameters through routing params or query, or large data can be processed with vuex.) This article mainly introduces the eventbus in Vue that is triggered multiple times and the pitfalls that have been stepped on. The editor thinks it is quite good. Now Share it with everyone, hope it can help everyone.
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 is 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 to control There is no output from the station. 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:
Question 1: Why is the on event in page B not triggered when it is triggered for the first time
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 I first conducted a test, that is, when jumping 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. , here is a picture 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 chart:
// 修改一下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 Dada proposed the following solution:
*That is to say, this $on event will not be automatically and clearly destroyed, and we need to manually destroy it. (However, I am not sure what the external bus here means. Can anyone explain it? You also mentioned that if the external bus is registered, it needs to be cleared) ****
所以。我在B组件页面中添加Bus.$off来关闭。代码如下:
// 在B组件页面中添加以下语句,在组件beforeDestory的时候销毁。 beforeDestroy () { bus.$off('get', this.myhandle) },
来看一下输出的结果
t可以看到,控制台第一次进去的时候就有输出,而且输出的不会逐次增加
*当然,尤大大还说可以写一个mixin?我还不知道是什么?以后在研究一下。
总结: 所以,如果想要用bus 来进行页面组件之间的数据传递,需要注意亮点,组件A$emit事件应在beforeDestory生命周期内。其次,组件B内的$on记得要销毁。
相关推荐:
The above is the detailed content of How to solve the problem of eventbus being triggered multiple times in Vue. For more information, please follow other related articles on the PHP Chinese website!

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver Mac version
Visual web development tools

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.