vue中使用keep-alive对组件进行缓存,关闭tag时清除缓存

7 篇文章 0 订阅
6 篇文章 0 订阅

**

场景: 后台管理系统中,列表进详情页,再次返回列表页,需要保存之前的搜索条件,这时需要使用keep-alive进行缓存,关闭tag标签时清除缓存。

**

1、router.js(对需要缓存的组件添加keepAlive)

{
      path: "/policy",
      name: "Policy",
      component: () => import("../views/pages/policy/index.vue"),
      meta: {
        keepAlive: true
      }  // true缓存 false不缓存
 }

2、App.vue

<template>
  <div id="app">
    <!-- <router-view /> -->
    <keep-alive>
      <router-view v-if="$route.meta.keepAlive" :key="fullPath"></router-view>
    </keep-alive>
    <router-view v-if="!$route.meta.keepAlive"></router-view>
  </div>
</template>

<script>
export default {
  name: "App",
  computed: {
    fullPath() {
      // console.log(this.$route.fullPath);
      return this.$route.fullPath;
    },
  },
  methods: {
    // 根据fullUrl清除keepAlive
    clearKeepAlive(fullUrl) {
      // console.log('bus触发要清除的keepAlive', fullUrl);
      this.$children.forEach((item) => {
        if (item.$vnode.data.key == fullUrl) {
          console.log(item.$vnode.data.key);
          this._myDestory(item);
        }
      });
    },
    // 封装清除某个组件的keepAlive状态,并销毁
    _myDestory(keepAliveComponent) {
      // 你可以根据自己的业务更改此处的判断逻辑,酌情决定是否摧毁本层缓存。
      if (
        keepAliveComponent.$vnode &&
        keepAliveComponent.$vnode.data.keepAlive
      ) {
        if (
          keepAliveComponent.$vnode.parent &&
          keepAliveComponent.$vnode.parent.componentInstance &&
          keepAliveComponent.$vnode.parent.componentInstance.cache
        ) {
          if (keepAliveComponent.$vnode.componentOptions) {
            var key =
              keepAliveComponent.$vnode.key == null
                ? keepAliveComponent.$vnode.componentOptions.Ctor.cid +
                  (keepAliveComponent.$vnode.componentOptions.tag
                    ? `::${keepAliveComponent.$vnode.componentOptions.tag}`
                    : "")
                : keepAliveComponent.$vnode.key;
            var cache =
              keepAliveComponent.$vnode.parent.componentInstance.cache;
            var keys = keepAliveComponent.$vnode.parent.componentInstance.keys;
            if (cache[key]) {
              if (keys.length) {
                var index = keys.indexOf(key);
                if (index > -1) {
                  keys.splice(index, 1);
                }
              }
              delete cache[key];
            }
          }
        }
      }
      keepAliveComponent.$destroy();
    },
  },
  mounted() {
    // 注册监听全局的clearKeepAlive方法,可在其他组件中触发此方法
    this.$bus.on("clearKeepAlive", this.clearKeepAlive);
  },
};
</script>

3、使用(在关闭tag的方法中)

closeTag(path) {
	this.$bus.emit("clearKeepAlive", path); // 清除缓存
}
  • 7
    点赞
  • 32
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值