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()
  },
相关推荐
Gatlin5 分钟前
前端逆向与反逆向:一场猫鼠游戏的底层逻辑与实战
前端
Pedantic8 分钟前
本地通知(Local Notifications)学习笔记
前端
森蓝情丶1 小时前
我给 AI 搭了个法庭:一个前端仔的 LangGraph 实战全记录
前端·后端
爱勇宝1 小时前
干了近 8 年,一夜之间被裁:AI 时代,程序员最该害怕的不是 AI
前端·后端·程序员
Pedantic1 小时前
Combine 框架学习笔记
前端
runnerdancer1 小时前
Agent如何加载执行Skill的脚本
前端·agent
yingyima2 小时前
VS Code 正则替换技巧:从凌晨3点的服务器报警开始
前端
默_笙2 小时前
🛬 我让 AI 帮我写了一个打飞机游戏,结果 Canvas 把我整不会了
前端·javascript
梯度不陡2 小时前
AI 到底能不能从零写软件?ProgramBench 和 RepoZero 给出了两种答案
前端·javascript·面试
冬奇Lab2 小时前
每日一个开源项目(第137篇):Penpot - 真正开源的设计协作工具,SVG 原生格式消灭设计-开发鸿沟
前端·开源·设计