KeepAlive on routes is set to true. Why does the page component state cache fail?

Cause: The keepAlive hierarchy is set in the routing configuration file. Solution: Set a unified keepAlive hierarchy in the project.Copy the code

If keepAlive is set to true, the memory is not reclaimed after the navigation TAB is closed, and the browser cache continues to increase. As a result, the browser crashes

Reason: keepAlive cache is a component, that is, vue virtual DOM → vNode. Do the same operation, open the submenu, close the TAB:Copy the code

As can be seen from the above figure, keepAlive has a memory leak

Keep-alive alternatives:

The keep-alive cache has a high memory usage for the virtual DOM. Try using the browser sessionStorage to cache TAB data. Monitor the change of $route in RouteView component watch to cache the current TAB data according to keepAlive state; 2. In the Updated hook of RouteView component, determine the keepAlive state of the routing page to be forwarded and synchronize cached data to the current page. 3. At the end of the removeTab method on the MutiTab component, clear the data cached on the current TAB.Copy the code

Code implementation: RouteView.vue

<script>

import { mapState } from 'vuex'; export default { name: 'RouteView', computed: { ... mapState('app', ['keepAliveNames']), cachedViews() { return this.keepAliveNames.map(x => x.value); }, key() { return this.$route.fullPath; } }, watch: { $route(to, from) { console.log(to, from); const childNode = this.$children[0]; If (childNode.$options.name! == 'RouteView' && from.meta.keepAlive) { sessionStorage.setItem(this.key, JSON.stringify(childNode.$data)); } } }, updated() { const childNode = this.$children[0]; if (childNode.$options.name ! == 'RouteView' && this.$route.meta.keepAlive) { const state = JSON.parse(sessionStorage.getItem(this.key)); // When the page is rendered, synchronize the cached data to the current page!! state && Object.assign(childNode.$data, state); } }, render() { return ( <router-view /> ); }}; </script>Copy the code

MutiTab.vue

Methods: {removeTab (targetKey) {/ / delete component state data cache sessionStorage. RemoveItem (targetKey); }}Copy the code

Improved effect: