vue项目中使用keep-alive定制化的缓存页面

223 阅读1分钟

store.ts

state:{
  cachePages:[]
},
mutations:{
  _setCachePage(state: any, cachePageName: string) {
    if (state.cachePages.indexOf(cachePageName) === -1) {
      state.cachePages.push(cachePageName);
    }
  },
  _clearCachePage(state: any, cachePageName: string) {
    let index: number = state.cachePages.indexOf(cachePageName);
    if (index !== -1) {
      state.cachePages.splice(index, 1);
    }
}

App.vue

<template>
  <div id="app">
    <keep-alive :include="cachePages">
      <router-view/>
    </keep-alive>
  </div>
</template>

<script lang="ts">
import {Component} from "vue-property-decorator";
import BaseComponentInherit from "@/utils/http.ts";
import {State} from "vuex-class";

Component.registerHooks([
  'beforeRouteEnter',
  'beforeRouteLeave'
])
@Component({})
export default class App extends BaseComponentInherit {
  @State cachePages: any;
}
</script>

xxxpage.vue

beforeRouteLeave(to: any, from: any, next: any) {
  // 如果不是回到上一个前一个页面,需要缓存页面,否则清除
  if (to.path !== '/prepage') {
    this._setCachePage('xxxpage')
  } else {
    this._clearCachePage('xxxpage')
  }
  setTimeout(next, 0)
}