Reasons and solutions for multiple executions of the watch method when Vue monitors route changes

Reasons and solutions for multiple executions of the watch method when Vue monitors route changes

I am a front-end rookie, and I have been committed to the uninterrupted production management of backend bugs, and use this to encourage myself. I received a request in recent days and searched many examples on the Internet, but the problem was not solved fundamentally. I will record my own solution process here. This is also the first time I speak in the Nuggets, so please be gentle.

Requirement description:

There are two pages, A and B. The orderId of page A needs to be passed to page B by routing parameters to perform data association query, and then displayed on page B.

Requirements analysis:

If you get this requirement, it should be easy for you to think of watching the route changes on page B, and then getting the parameters to execute the method of querying data.

Solving needs

In page A:

const route = {
        name: 'BpageName',
        params: { orderId: this.tableData[index].id },
        meta: {
          title: 'Page B'
        }
      }
this.$router.push(route)

Push a route to reopen page B

Then page B accepts the routing parameters:

@Watch('$route.params.packageId')
routeParamsChanged(newParams: any, oldParams: any) :void { // Re-copy parameters by monitoring changes in passed parameters if (newParams) {
      this.getList(newParams)
    }
}

Doesn’t it look simple?

But the problem is that because page B has a keep-alive page cache, the routeParamsChanged method is only executed once when the route is switched for the first time, achieving the expected effect. However, if you close page B or jump from page A to page B without closing page B, the routeParamsChanged method will be triggered twice or more.
After checking a lot of information, the problem of repeated triggering of functions in the Vue project watch explains the reasons for this situation.

Solution 1: Determine whether fullPath is page A

if (this.$route.fullPath === 'A page routing path') {
    // do something
}

I tried it with excitement.

@Watch('$route')
routeParamsChanged(newParams: any, oldParams: any) :void { // Re-copy parameters by monitoring the changes in the passed parameters if (newParams === '/Apage') {
      this.getList(newParams)
    }
}

The result is still not working, the routeParamsChanged method will still be executed twice or more times. Solution 2: Add a flag parameter to determine whether the page is in the active state. Components using keep-alive cache will only trigger activated and deactivated events, so set the flag to true and false when these two events are triggered. GetList() is executed only when the flag is true.

private activatedFlag: boolean = false
activated () {
    this.activatedFlag = true;
}

deactivated () {
    this.activatedFlag = false;
}
@Watch('$route')
routeParamsChanged(newParams: any, oldParams: any) :void { // Re-copy parameters by monitoring changes in passed parameters if (newParams && this.activatedFlag) {
      this.getList(newParams)
    }
}

Has this been fixed this time? The result is still not working, the routeParamsChanged method will still be executed twice or more times. Crashing...

Problem Solving

Drawing on the solution 2 above, we can finally implement the method of obtaining parameters and calling the method of obtaining data in the activated () lifecycle hook function. We don’t need to listen to the changes in the route. We can just obtain the data by obtaining this.$route.params.orderId.

private activatedFlag: boolean = false
activated () {
    this.activatedFlag = true
    if (this.$route.params.orderId && this.activatedFlag) {
      this.getList(this.$route.params.orderId)
    }
}

deactivated () {
    this.activatedFlag = false;
}

It’s done, finally solved. Dear experts, please give some comments on the code. If you have better opinions or suggestions, please leave comments and provide guidance.

The above is the detailed content of the reasons and solutions for why the watch method is executed multiple times when Vue monitors route changes. For more information about the reasons and solutions for why the Vue watch method is executed multiple times, please pay attention to other related articles on 123WORDPRESS.COM!

You may also be interested in:
  • Example of Vue routing listening to dynamically load the same page
  • Vue uses routing hook interceptors beforeEach and afterEach to listen to routing
  • Vue listens to the browser's native return button to perform route jump operations
  • Vue listens to route changes and refreshes the page in the App.vue file
  • Vue routing cache routing nested routing guard listens to physical return operations
  • Summary of several ways for Vue to monitor route changes

<<:  MySQL 5.7.19 (tar.gz) installation graphic tutorial under Linux

>>:  How to build svn server in linux

Recommend

Summary of Vue's cross-domain problem handling and solutions

When you send a network request, the following sa...

Use auto.js to realize the automatic daily check-in function

Use auto.js to automate daily check-in Due to the...

CSS shadow animation optimization tips

This technique comes from this article - How to a...

JavaScript method to detect the type of file

Table of contents 1. How to view the binary data ...

Solution to SNMP4J server connection timeout problem

Our network management center serves as the manag...

JavaScript basics of this pointing

Table of contents this Method In the object Hidde...

mysql 5.7.17 winx64.zip installation and configuration method graphic tutorial

Preface: I reinstalled win10 and organized the fi...

Example code for implementing background transparency and opaque text with CSS3

Recently, I encountered a requirement to display ...

Detailed tutorial on deploying apollo with docker

1. Introduction I won’t go into details about apo...

Detailed explanation of Vite's new experience

What is Vite? (It’s a new toy on the front end) V...

CSS implements Google Material Design text input box style (recommended)

Hello everyone, today I want to share with you ho...

How to completely uninstall mysql under CentOS

This article records the complete uninstallation ...