vue keep-alive life cycle
keep-aliveIt is a built-in component provided by Vue to cache components - keeping the state in memory during component switching to prevent repeated rendering of the DOM.
If a component is wrapped with keep-alive, it will have two additional life cycles: deactivated and activated.
Meanwhile, beforeDestroy and destroyed will not be triggered again because the componentWill not be truly destroyed。
When keep-alive is introduced, the page enters for the first time, the triggering order of the hook is created-> mounted-> activated, and the deactivated is triggered when exiting.
When entering again (forward or backward), only activated is triggered.
Dynamic components or router-views wrapped by keep-alive will cache inactive instances. These cached instances will be reused again when called again. For some of our pages that do not require real-time updates, it greatly reduces performance consumption and does not need to send HTTP requests again. However, there is also a problem that the data we request to obtain will not be re-rendered on the page again. This also occurs. For example, if we use dynamic routing to match, the page will only maintain the rendering result of the first requested data, so we need to force refresh certain components in specific situations.
1.Use include and exclude attributes
<keep-alive include="orderList"> <router-view></router-view> </keep-alive> <keep-alive exclude="index"> <router-view></router-view> </keep-alive>
Include attribute means that only components with name attribute of orderList will be cached (note that it is the name of the component, not the name of the route). Other components will not be cached. Exclude attribute means that except for components with name attribute of index, it will not be cached, other components will be cached.
2. Utilize meta attributes
export default[ { path:'/', name:'home', components:Home, meta:{ keepAlive:true //Components that need to be cached }, { path:'/orderList', name:'orderList', components:Book, meta:{ keepAlive:false //Components that do not need to be cached } ]
<keep-alive> <router-view v-if="this.$"></router-view> <!--Here is the cached component--> </keep-alive> <keep-alive v-if="!this.$"></keep-alive> <!--This is a component that will not be cached-->
Summarize
The above is personal experience. I hope you can give you a reference and I hope you can support me more.