The front-end Vue route returns the status of the recovery page

Time:2022-5-4

Demand scenario: search the content on the home page, click to jump to the details page, return to the home page and keep the search results.

Scheme: routing parameters; Route guard

Requirement description

When using Vue to develop the front end, we encounter a scenario: conduct some data search on the home page, click the search results to enter the details page, browse the details page and return to the home page. But at this time, the previous search records and page turning disappear, and the user experience is not good. Therefore, you need to restore the page parameter state before jump after returning.

Of course, if conditions permit, the easiest way is to click the search results and open it with a new page (such as Baidu). However, the current demand is a complete Vue development project, which does not open the off-site address, and there are not many details. It is not appropriate to use new pages (poor performance and easy to manufacture a large number of tabs).

Here are two solutions that are easy to implement:

  • Scheme 1: store the search parameters in the route parameter (route. Query), and search according to the parameters when loading the page

    • Advantages: refresh does not affect; Simple implementation
    • Disadvantages: parameters can only be foundation type and length is limited; The path looks ugly; Only valid for browser return, manual jump back to the home page is not allowed
  • Scheme 2: use the route guard hook to store the page parameters (vuex, local storage, etc.) locally before leaving the page

    • Advantages: parameter types and lengths are relatively free; The path looks fresh and beautiful; It is valid for returning to the home page in any way
    • Disadvantages: additional data storage operation is required. If store mode or vuex is used, the refresh page will be invalid

Scheme 1: routing parameters

If you don’t have many parameters and don’t mind having a large string of parameters behind the path (tears of obsessive-compulsive disorder), you can directly put the parameters in the routing path (such as Baidu:baidu.com/s?wd=abc&rsv_spt=1&rsv_iqid=0x8a76279a000e2979&..., as you can see, it’s really a long string).

After clicking search, use Vue router to jump and transfer parameters:

//Search page

search(param) {
  //Other processing
  this.$router.push({
      name: "Index",
      query: { ...this.queryParam }, 	//  Expand objects to key values
  });
},

Note the difference between query parameters and params parameters: the parameters of the former will be?k1=v1&k2=v2The form of continues behind the path and can be seen directly in the address bar, so it is not affected by page Jump and refresh; The latter only works when you jump to the corresponding page for the first time, and then refresh the jump. Therefore, we need to use query to pass parameters here. It is also possible to manually write the parameters in the path according to the format, but the readability and scalability are obviously worse. It is not recommended unless there are only one or two simple parameters.

In addition, because this parameter is to be put into the path, it can only be a basic type of key value pair, and arrays or objects cannot be well supported. If the parameter is simple, you can expand the corresponding object as a parameter (you need to ensure that there is no duplicate name key in different objects), but when you jump to the search result page, you can only get it attribute by attribute.

//Search results page

mounted() {
  //Distinguish between $route and $route
  if (this.$route.query.type) {
    let type = this.$route.query.type;
    let keyword = this.$route.query.keyword;
    // ... Get each parameter one by one
    //Search operation
  } else {
    //There are no search parameters (because my search results and the home page are the same page, it may just open the home page normally)
  }
},

Scheme 2: local storage parameters

Since the parameters I want to save are three objects, it is inconvenient to expand them into key values, so I use this scheme. Because vuex was originally used in the project, it was stored in vuex by the way. It can be stored anywhere according to the actual situation. The disadvantage of vuex is that it is wiped out as soon as it is refreshed, which has little impact on the function of optimizing the experience nature of search results; If there are corresponding requirements, they can be stored in local storage.

Because there are many ways to change parameters in my requirements, it is too troublesome to store parameters when changing, and it is easy to make mistakes or omit. Therefore, we choose to uniformly store the required parameters before routing jump.

Vue router providesRoute navigation guardA series of APIs to realize corresponding functions, including global pre / parse / post guard, route configuration guard, component guard, etc. The so-called “guard” is actually equivalent to the “hook” in the rendering process, which is the same as the familiar created and mounted.

Complete navigation analysis process:

  1. Navigation is triggered.
  2. Called in an inactive componentbeforeRouteLeaveGuard.
  3. Call GlobalbeforeEachGuard.
  4. Call in reused componentsbeforeRouteUpdateGuard (2.2 +).
  5. Call in routing configurationbeforeEnter
  6. Resolve asynchronous routing components.
  7. Called in the activated componentbeforeRouteEnter
  8. Call GlobalbeforeResolveGuard (2.5 +).
  9. Navigation confirmed.
  10. Call GlobalafterEachHook.
  11. Trigger DOM update.
  12. callbeforeRouteEnterPass it to the guardnextThe created component instance will be passed in as a parameter of the callback function.

Obviously, it is used herebeforeRouteLeaveThe hook can well meet the requirements:

//Search results page

beforeRouteLeave(to, from, next) {
  //Vuex storage operation
  this.$store.commit("updateRevert", {
    query: this.queryParam,
    page: this.pageParam,
    filter: this.filter,
  });
  next(); 	//  Continue the subsequent navigation parsing process
},

When loading the page, check whether there are saved parameters, and if so, restore them accordingly:

//Search results page

mounted() {
  //Judge whether there are saved search parameters in vuex
  if (this.$store.state.revert) {
    const revert = this.$store.state.revert;
    this.queryParam = revert.query;
    this. pageParam = revert. page; 	//  You can take out the whole object directly
    //Search operation
  } else {
    //There are no search parameters (because my search results and the home page are the same page, it may just open the home page normally)
  }
},

Conclusion & References

The above is the sharing of two ways to save page status. Many of these choices are related to the actual needs at that time, so they are not necessarily the best solution in all scenarios. For your specific needs, there may be deficiencies in the scheme in the article, or there may be simpler methods; The actual requirements and basis of each step are explained as much as possible for reference. For the omissions and deficiencies in the article, please discuss and correct them in the comments.

Programming navigation

Route navigation guard