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()
  },
相关推荐
Alex艾力的IT数字空间24 分钟前
在 Kylin(麒麟)操作系统上搭建 Docker 环境
大数据·运维·缓存·docker·容器·负载均衡·kylin
发现一只大呆瓜29 分钟前
深度解密 Rollup 插件开发:核心钩子函数全生命周期图鉴
前端·vite
aXin_ya1 小时前
Redis 高级篇(最佳实践)
数据库·redis·缓存
java_nn1 小时前
一文了解前端技术
前端
发现一只大呆瓜1 小时前
深度解析 Rollup 配置与 Vite 生产构建流程
前端·vite
小码哥_常2 小时前
安卓黑科技:让手机成为你的“跌倒保镖”
前端
小李子呢02112 小时前
前端八股Vue---Vue2和Vue3的区别,set up的用法
前端·javascript·vue.js
m0_647057962 小时前
Harness Engineering 实践指南
前端
邂逅星河浪漫3 小时前
【银行内网开发-管理端】Vue管理端+Auth后台开发+Nginx配置+Linux部署(详细解析)
linux·javascript·css·vue.js·nginx·html·前后端联调
JJay.3 小时前
Android BLE 稳定连接的关键,不是扫描,而是 GATT 操作队列
android·服务器·前端