Vue 缓存机制

1. 在 store.js 中设置全局的 数据存储字段

js 复制代码
    // 是否缓存
    keepAlivePage: [],


mutations : 
	CHANGE_KEEP_ALIVE(state, data) {
      	state.keepAlivePage = data
    },

actions: {//类似 mothods,异步
    // 页面缓存
    setKeepAlivePage({
      commit
    }, data) {
      commit("CHANGE_KEEP_ALIVE", data)
    },
  }

2.在 自定义的 set.js 中设置全局方法

js 复制代码
import moment from 'moment'

export default {
  install(Vue) {
    // 增加缓存页面
    Vue.prototype.addKeepAlive = function (componentName) {
      let alivePage = this.$store.state.keepAlivePage.slice(0)
      alivePage.push(componentName)
      alivePage = Array.from(new Set(alivePage))
      this.$store.dispatch('setKeepAlivePage', alivePage)
      console.log(this.$store.state.keepAlivePage, "当前缓存的页面1")
    }
    // 删除缓存页面
    Vue.prototype.deleteKeepAlive = function (componentName) {
      let alivePage = this.$store.state.keepAlivePage.slice(0)
      alivePage.forEach((item, index) => {
        if (item == componentName) {
          alivePage.splice(index, 1)
        }
      })
      alivePage = Array.from(new Set(alivePage))
      this.$store.dispatch('setKeepAlivePage', alivePage)
      console.log(this.$store.state.keepAlivePage, "当前缓存的页面2")
    }
  }
}

3.在 App.vue 中设置缓存

js 复制代码
  <keep-alive :include="keepAlivePage">
      <router-view></router-view>
    </keep-alive>
  computed: {
    ...mapState(["keepAlivePage"]),
  },

4. 在页面中使用

js 复制代码
beforeRouteLeave(to, from, next) {
    const _this = this;
    console.log(to.name, from.name, "beforeRouteLeave")
    // 如果跳转到详情页面走缓存
    if (
      to.name == "productetails"
    ) {
      _this.addKeepAlive(from.name);
    } else {
      _this.deleteKeepAlive(from.name);
    }
    next()
  },

或者

  beforeRouteLeave(to, from, next) {
    const _this = this;
    // console.log(to.name, from.name, "beforeRouteLeave")
    // console.log(_this.$options.name, "beforeRouteLeave")
    // 如果跳转到详情页面走缓存
    if (
      to.name == "upcomplaintDetail" ||
      to.name == "storeexamine" ||
      to.name == "dealerexamine" ||
      to.name == "sbuexamine" ||
      to.name == "masterexamine" 
    ) {
      _this.addKeepAlive(_this.$options.name);
    } else {
      _this.deleteKeepAlive(_this.$options.name);
    }
    next()
  },
相关推荐
ZC跨境爬虫33 分钟前
跟着 MDN 学 HTML day_37:(深入掌握 CustomEvent 自定义事件接口)
前端·javascript·ui·html·音视频
码海扬帆:前端探索之旅8 小时前
深度定制 uni-combox:新增功能详解与实战指南
前端·vue.js·uni-app
谷雨不太卷8 小时前
进程的状态码
java·前端·算法
打小就很皮...8 小时前
基于 Python + LangChain + RAG 的知识检索系统实战
前端·langchain·embedding·rag
BJ-Giser8 小时前
Cesium 烟雾粒子特效
前端·可视化·cesium
空中海8 小时前
02 ArkTS 语言与工程规范
java·前端·spring
YJlio8 小时前
7.4.5 Windows 11 企业网络连接与网络重置实战:远程访问、本地策略与故障恢复
前端·chrome·windows·python·edge·机器人·django
Slow菜鸟8 小时前
Codex CLI 教程(五)| Skills 安装指南:面向 Java 全栈工程师打造个人 ECC(V1版)
大数据·前端·人工智能
2501_912784088 小时前
TaoCarts 反向海淘系统架构:1688自动代采与高并发缓存设计全解析
缓存·系统架构·跨境电商·taocarts
Lee川8 小时前
打字机是怎么炼成的:Chat 流式输出深度解析
前端·后端·面试