When using keep-alive to cache components, the timers in the component may continue to run after the component is cached, interfering with the logic of other components. To avoid this, it can be solved by:
1. Clean the timer in the component's deactivated hook
keep-alive provides activated and deactivated lifecycle hooks for cached components. The timer can be cleaned in the deactivated hook to ensure that the timer does not continue to run when the component is cached.
export default { data() { return { timer: null }; }, activated() { // Restart the timer when the component is activated (); }, deactivated() { // Clean the timer when the component is cached (); }, methods: { startTimer() { (); // Prevent timer from repeatedly setting = setInterval(() => { ('The timer is running...'); }, 1000); }, clearTimer() { if () { clearInterval(); = null; } } } };
2. Use the beforeDestroy hook to clean the timer
If the component may be destroyed (for example, when the max property of keep-alive limits the number of caches), you can clean the timer in the beforeDestroy hook.
export default { data() { return { timer: null }; }, beforeDestroy() { (); }, methods: { startTimer() { (); = setInterval(() => { ('The timer is running...'); }, 1000); }, clearTimer() { if () { clearInterval(); = null; } } } };
The implementation principle of keep-alive
keep-alive is a built-in abstract component of Vue that is used to cache dynamic or routing components to avoid repeated creation and destruction of components. Its core principle is as follows:
- Cache component instance:
When a component is loaded for the first time, keep-alive caches the component instance to the object. The cached component instance is the component's key
is a key, and the virtual node of the component is a value.
- Multiplex cache instance:
When switching to a cached component again, keep-alive will remove the corresponding component instance from it instead of recreating it.
By adjusting the order, make sure that the most recently used component instances are always at the end of the cache list.
- Lifecycle management:
keep-alive introduces activated and deactivated life cycle hooks. Triggered when the component is activated
activated, triggers deactivated when the component is cached.
- Clean the cache:
If the max property is set, the earliest cached components will be cleaned when the number of cached components exceeds max.
Destroy component instances through the pruneCacheEntry function and remove them from the cache.
This is the article about quickly solving the timer interference problem in keep-alive cache component. For more related contents of keep-alive cache component, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!