Keep-alive is a component built into VUE. When a component is wrapped with keep-Alive, inactive component instances are cached rather than destroyed. It is used to save component state or avoid duplicate creation. Avoid performance issues caused by repeated rendering.
The characteristics of
- It is an abstract component that does not render a DOM element on its own and does not appear in the component’s parent chain.
- When a component is switched in keep-alive, the component’s lifecycle hook functions activated and deactivated are executed. Created and Mounted hooks are not executed once a component is cached.
- Requires that only one child component be rendered at a time.
- Does not work properly in functional components because they do not cache instances.
Usage scenarios
// 1 Dynamic components (dynamic components are components that use the same mount point and switch dynamically.)
<keep-alive>
<component is="currentComponent"></component>
</keep-alive>
// 2 Subcomponents of multiple conditional judgments
<keep-alive>
<comp-a v-if="true"></comp-a>
<comp-b v-else></comp-b>
</keep-alive>
// 3 transition
<transition>
<keep-alive>
<component is="currentComponent"></component>
</keep-alive>
</transition>
// 4 Combine vue-router
<keep-alive>
<router-view></router-view>
</keep-alive>
Copy the code
props
-
Include whitelists are cached only for components whose names match
-
Exclude Blacklist Any matching component will not be cached
-
Max Specifies the maximum number of instances to cache. Once this number is reached, the longest unaccessed instances of cached components are destroyed before new instances are created. LRU algorithm
Note: Include and exclude first check the component’s name attribute, and if name is not available, match the locally registered name. The anonymous component could not be matched.
keywords
The cache does not let components be destroyed
Keep-alive implementation principle
The component gets the first child node through the slot. Check whether the cache is required based on include and exclude, and check whether the cache is matched based on the key of the component. Using THE LRU algorithm, update the cache and the corresponding keys array. Controls the maximum number of components in the cache based on Max.
The business requirements
-
When jumping to the details page, keep the scroll bar of the list page at the same depth. This improves the user experience. In Vue, this need for “page caching” can be addressed using the Keep-alive component.
-
In A recent development, three pages A, B and C were designed. Imagine A scenario requirement like this:
- Leave page B to page C and cache data from page B (keepAlive: true)
- Leave page B and enter page A without caching page B data (keepAlive: false)
Reference:
- The official documentation
- VUE cache: dynamic keep-alive