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()
  },
相关推荐
skiy2 小时前
redis 使用
数据库·redis·缓存
huabiangaozhi2 小时前
spring-boot-starter和spring-boot-starter-web的关联
前端
奕成则成2 小时前
Redis 大 Key 问题排查与治理:原因、危害、实战方案
数据库·redis·缓存
umeelove352 小时前
Spring boot整合quartz方法
java·前端·spring boot
小码哥_常2 小时前
Android 开发探秘:View.post()为何能获取View宽高
前端
爱学习的程序媛2 小时前
【Web前端】WebAssembly详解
前端·web·wasm
不会写DN3 小时前
Js常用的字符串处理
开发语言·前端·javascript
晓13133 小时前
第三章 TypeScript 高级类型
前端·javascript·typescript
一勺菠萝丶3 小时前
芋道项目部署时,前端和门户网站如何通过 Nginx 转发后台接口,而不直接暴露后端地址
运维·前端·nginx