Vue uses keep-alive cache and destroy cache state

Vue uses keep-alive cache and destroy cache state

need

The page needs to save the operation state, and destroy the cache state when the tab is closed

accomplish

  • Set the routing attribute keepAlive corresponding to the page that needs to save the state to true
  • Use the include or exclude attribute in keep-alive
    Add the keepAlive attribute
    Add it yourself according to the dynamic routing and static routing method you use, add the location
{
     name:'a'
     path:'/A',
     component:()=>import('@/pages/A'),
     meta:{
         title:'A页面'
     }
 },

After the addition is complete, add the include attribute to the page html. The include will be selectively cached. If there is no one, it will not be cached. The exclude will be the opposite.
By adding and deleting the include attribute value, which pages are saved and destroyed
in combination with the label component. Set the tagNames value in vuex to become a global shared variable.
Set tagNames in vuex, here use the array historys displayed by the tag to get

state: {
	historys: [],
},
 mutations: {
	SETHISTORYS(state, historys) {
		state.historys = historys
	}
},
 actions: {
	setHistorys({ commit },historys) {
		commit("SETHISTORYS", historys)
	},
 },
 getters:{
	historys(state){
		return state.historys
	},
	/** 标签名称列表 */
	tagNames(state){
		return state.historys.map(function(tag){return tag.name})
	}
 }
<template>
  <div>
    <keep-alive :include="tagNames">
      <router-view v-if="$route.meta.keepAlive"></router-view>
    </keep-alive>
    <router-view v-if="!$route.meta.keepAlive"></router-view>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
export default {
  name: "superAdmin",
  computed: {
    ...mapGetters("history", ["tagNames"]),
  },
};
</script>
<style lang="scss"></style>

What needs to be noted here is: because include and exclude make the tag act on all vue pages whose name attribute value is consistent with the attribute value of this tag include or exclude (note that it is not to assign a value to the name of the route)

Guess you like

Origin blog.csdn.net/weixin_46995731/article/details/122620986