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()
  },
相关推荐
就叫_这个吧1 小时前
HTML常用标签及举例使用
前端·html
utf8mb4安全女神1 小时前
【rsyslog服务】把所有服务的“临界点”以上的错误都保存在/var/log/alert.log⽇志中
java·前端·javascript
YANQ6621 小时前
7.bundlesdf本地安装
前端·webpack·node.js
星夜夏空992 小时前
FreeRTOS学习(7)——任务列表
java·前端·学习
weixin_471383032 小时前
由浅入深递归练习
前端·javascript·vue.js
tedcloud1232 小时前
ai-engineering-from-scratch部署教程:从零搭建AI应用环境
服务器·前端·人工智能·系统架构·edge
Kurisu5752 小时前
全面战争:战锤3修改器下载2026最新
前端
丷丩2 小时前
MapLibre GL JS第21课:绘制GeoJSON点图标、注记
前端·javascript·gis·mapbox·maplibre gl js
LCG元3 小时前
现代Web应用高可用架构设计与性能调优实战
前端·wpf
步十人3 小时前
【Redis】持久化机制
数据库·redis·缓存