由于项目里遇到这个需求,于是在网上搜索了一下,几乎都是使用keep-alive,然后给路由配置里设置缓存为true,但是这样并不能满足需求,而是造成了第一次打开页面确实加载刷新了,然后只要打开过,后面就再也不会刷新,有点坑。

下面写一下我的解决方案:

1.stroe.js文件

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)

const state = {
    catchArr: '',
}

const getters = {
}

const mutations = {
    iskeepAlive(state, component) {
        state.catchArr = component
    },
    noKeepAlive(state, component) {
        state.catchArr = []
    },
}

const actions = {
}

export default new Vuex.Store({
    state,
    mutations
})

2.App.vue文件

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

<script>
export default {
  name: "app",
  created() {},
  data() {
    return {
      cached: this.$store.state.catchArr,
    };
  },
  watch: {
    $route: {
      handler: function (to, from) {
        this.cached = this.$store.state.catchArr;
      },
    },
  },
  methods: {},
};
</script>

3.main.js

import Vue from 'vue'
import App from './App.vue'
import VueRouter from 'vue-router'
import routes from './router'

import store from './store/index'
Vue.use(VueRouter);
Vue.config.productionTip = false

import Vant from 'vant';
import 'vant/lib/index.css';

Vue.use(Vant);

let router = new VueRouter({
  mode: 'hash',
  routes
})


router.beforeEach((to, from, next) => {
  // 对组件进行动态缓存
  if (to.name == 'express' || to.name == 'eqWarning' || to.name == "prediction") {
    store.commit('iskeepAlive', to.name);
  }
  next();
})

new Vue({
  router,
  store,
  render: h => h(App),
}).$mount('#app')

4.具体组件页面,这里以express.vue举例,这里特别要注意的是App.vue里面的keep-alive里include的值为组件页面里name设置的值,而非route里面配置的name。

<script>
export default {
  name: "express",//主要是这个name的值
  data() {
    return {
    };
  },
  created() {},
  beforeRouteLeave(to, from, next) {
    if (
      to.name != "imcatalogDetail" &&
      to.name != "disasterDetail" &&
      to.name != "intensityDetail"
    ) {
      this.$store.commit("noKeepAlive", "express");
    } else {
      this.$store.commit("iskeepAlive", "express");
    }
    next();
  },
  methods: {   
  },
};
</script>

本文参考了这篇文章:Vue动态改变keepAlive缓存

Logo

前往低代码交流专区

更多推荐