SoFunction
Updated on 2025-03-02

Detailed explanation of what to pay attention to when opening keep-alive in Vue2.0 route

Vue2.0 has the necessary requirement for application. Page data needs to be cached. You don’t have to request the data again every time you enter the page. Each page switch has a period of waiting for the corresponding time. This user experience is so uncomfortable, so page caching is necessary. When do you need to update the page data? You can listen to the status changes, or manually pull down to refresh and re-request data. Jiang Zi, I think the user experience will do better.

The effects and benefits of keep-alive

In e-commerce related projects, when we first enter the list page, we need to request data. When I enter the details page from the list page, the details page do not cache and also need to request data, and then return to the list page. At this time, we use keep-alive to cache components to prevent secondary rendering, which will greatly save performance.

If you don’t say much nonsense, you can directly upload the code. Generally, keep-alive is enabled in the src/ setting to realize page data cache:

<template>
 <keep-alive>
  <router-view></router-view>
 </keep-alive>
</template>

List several commonly used hook methods, as follows:

export default {
 data() {
  return {
  
  }
 },
 created: function() {
  ("the hook of created is done!");
 },
 mounted: function() {
  ("the hook of mounted is done!");
 },
 activated: function() {
  ("the hook of activated is done!");
 },
 deactivated: function() {
  ("the hook of deactivated is done!");
 }
}

The trigger order of the hook for the first time is created-> mounted-> activated, and the trigger is deactivated when exiting:

//Console printing results
the hook of created is done!
the hook of mounted is done!
the hook of activated is done!
the hook of deactivated is done!

The second time hook only triggers activated, and triggers deactivated when exiting:

//Console printing results
the hook of activated is done!
the hook of deactivated is done!

So that's why some people no longer trigger the pageInt methods registered by created and mounted after turning on keep-alive, because keep-alive blocks them, which means caches the data, so they no longer requests.

If you must request some of your pages in real time, you can directly do pageInt in the activated hook, and don't register the pageInt method on created and mounted.

You can also selective pageInt, such as listening status changes, including but not limited to listening route changes, changes in a certain parameter, changes in a certain time node, etc.

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.