vue使用keep-alive 缓存和销毁缓存状态

vue使用keep-alive 缓存和销毁缓存状态

需求

页面需要保存操作状态,在页签关闭的时候销毁缓存状态

实现

  • 把需要保存状态的页面对应的路由属性keepAlive设置为true
  • 使用了 keep-alive里面的 include或exclude属性
    添加keepAlive属性
    根据自己使用的动态路由和静态路由方式自行添加,添加位置
{
     name:'a'
     path:'/A',
     component:()=>import('@/pages/A'),
     meta:{
         title:'A页面'
     }
 },

添加完成后页面html加入include属性,include会选择性的缓存,没有的会选择不缓存,exclude则相反,
通过对include属性值的添加和删除,实现哪些页面的保存与销毁
结合标签组件来实现,在vuex中设置tagNames值,变为全局共享变量.
在vuex中设置tagNames,这里利用标签显示的数组historys获取

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>

这里需要注意的是:因为include和exclude 使该标签作用于所有name属性的值跟此标签 include或exclude的属性值一致的vue页面(注意不是给route的name赋值)

猜你喜欢

转载自blog.csdn.net/weixin_46995731/article/details/122620986
今日推荐