vue3 移动端 组件 前进缓存 后退不缓存

上份工作也遇到了这个问题,但没仔细研究,新入职的公司测试要求比较高,今天仔细看了下,百度了半天,没百度到合适的,自己动手丰衣足食了,终于在下班时搞出来了,真是也太开心啦~~

使用keep-alive 组件缓存,vue3中在APP.vue的写法:

  <router-view v-slot="{ Component }">
    <keep-alive :exclude="aliveComponent">
      <component :is="Component" />
    </keep-alive>
  </router-view>

用eventBus 事件总线来控制组件是否需要缓存:

//引入了插件,注意全局只能使用同一个emitter
import mitt from 'mitt'
export const emitter = mitt()

默认所有页面都进行缓存,用:exclude="aliveComponent" ,排除不需要缓存的组件,可以实现动态更改组件是否缓存

aliveComponent: "NewQueue,ReleaseSet" //不需要缓存的组件页面名

    // 添加不缓存组件
    function setNotAliveComponent(keyword: String) {
      let aliveItems = datas.aliveComponent;
      aliveItems =
        keyword +
        "," +
        aliveItems
          .split(",")
          .filter((e: String) => e != keyword)
          .join(",");
      if (aliveItems.substr(aliveItems.length - 1, 1) == ",") {
        aliveItems = aliveItems.substring(0, aliveItems.length - 1);
      }
      datas.aliveComponent = aliveItems;
    }

    // 移除不缓存组件
    function removeNotAliveComponent(keyword: String) {
      let aliveItems = datas.aliveComponent;
      let arr: Array<string> = aliveItems.split(",");
      arr.filter((e: String, index: number) => {
        if (e == keyword) {
          arr.splice(index, 1);
        }
      });
      aliveItems = arr.join(",");
      datas.aliveComponent = aliveItems;
    }

    //接收 添加 不缓存组件 事件
    emitter.on("add-no-alive-compt", (e) => {
      setNotAliveComponent(e);
    });

    //接收 移除 不缓存组件 事件
    emitter.on("remove-no-alive-compt", (e) => {
      removeNotAliveComponent(e);
    });

然后,在需要缓存的页面中触发事件

// 在不需要组件缓存时,比如在后退按钮中 添加 【不需要缓存组件】
emitter.emit("add-no-alive-compt", "Queue");

// 在需要组件缓存时,比如在前进页面前 移除 【不需要缓存组件】
emitter.emit("remove-no-alive-compt", "Queue");

这里主要是混合开发中的H5,如果后退使用到浏览器自带的后退功能,要结合路由来判断当前页面是否后退来进行触发添加 是否缓存事件了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值