天天看點

VUE路由動态緩存:傳回上頁面不重新整理,再次進入該頁面重新整理

由于項目裡遇到這個需求,于是在網上搜尋了一下,幾乎都是使用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緩存

繼續閱讀