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

A brief introduction to MySQL database optimization techniques

A mature database architecture is not designed wi...

Detailed introduction and usage examples of map tag parameters

Map tags must appear in pairs, i.e. <map> .....

Two ways to visualize ClickHouse data using Apache Superset

Apache Superset is a powerful BI tool that provid...

Steps to solve the MySQL 8.0 time zone problem

Software Version Windows: Windows 10 MySQL: mysql...

Detailed explanation of semiotics in Html/CSS

Based on theories such as Saussure's philosop...

Play with the connect function with timeout in Linux

In the previous article, we played with timeouts ...

Detailed installation and configuration tutorial of PostgreSQL 11 under CentOS7

1. Official website address The official website ...

How to get the maximum or minimum value of a row in sql

Original data and target data Implement SQL state...

Detailed explanation of creating, calling and managing MySQL stored procedures

Table of contents Introduction to stored procedur...

Explaining immutable values ​​in React

Table of contents What are immutable values? Why ...

VMware ESXi installation and use record (with download)

Table of contents 1. Install ESXi 2. Set up ESXi ...

Analysis of Alibaba Cloud CentOS7 server nginx configuration and FAQs

Preface: This article refers to jackyzm's blo...

Example code for implementing equal height layout in multiple ways with CSS

The equal height layout described in this article...

How to implement HTML Table blank cell completion

When I first taught myself web development, there...