vue路由实现前进刷新后退不刷新功能

需求

有A->B->C三个页面,要实现A页面进入B页面,B页面重新获取数据。从C页面返回到B页面,B页面有缓存,不用重新获取数据。

实现方法

包裹动态组件时,会缓存不活动的组件实例,而不是销毁它们。的include属性对应匹配的组件将会被缓存。在vuex声明一个数组变量作为include属性的值。在B页面上使用beforeRouteEnter内给变量数组添加B页面组件名添加缓存,beforeRouteLeave如果不是跳转到C页面,就删除变量数组中B页面的组件,删除缓存。

1.在vuex声明一个数组变量keepAlive,存放需要缓存路由组件name

vuex的index.js

import Vue from "vue";
import Vuex from "vuex";

Vue.use(Vuex);

export default new Vuex.Store({
     
  state: {
     
    keepAlive: [] //需要缓存(keep-alive)的路由组件name
  },
  mutations: {
     
	 //添加缓存组件
    keepAliveAdd(state, data) {
     
      let keepAliveArr = state.keepAlive;
      let key = true;
      for (let index = 0; index < keepAliveArr.length; index++) {
     
        const element = keepAliveArr[index];
        if (element == data) {
     
          key = false;
        }
      }
      if (key) {
     
        state.keepAlive.push(data);
      }
    },
    //删除缓存组件
    keepAliveDel(state, data) {
     
      let keepAliveArr = state.keepAlive;
      for (let index = 0; index < keepAliveArr.length; index++) {
     
        const element = keepAliveArr[index];
        if (element == data) {
     
          keepAliveArr.splice(index, 1);
        }
      }
    }
  }
});

2.APP.vue添加keep-alive

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

<script>
import {
       mapState } from "vuex";

export default {
     
  name: "App",
  computed: {
     
    ...mapState(["keepAlive"])
  }
};
</script>

3.B页面中通过路由导航守卫控制缓存

<script>
import {
      mapMutations } from "vuex";

export default {
     
  name: "B",
  beforeRouteEnter(to, from, next) {
     
    next(vm => {
     
      // 通过 `vm` 访问组件实例
      vm.keepAliveAdd("B");
    });
  },
  beforeRouteLeave(to, from, next) {
     
    if (to.name != "C") {
     
      this.keepAliveDel("B");
    }
    next();
  },
  methods: {
     
    ...mapMutations(["keepAliveAdd"]),
    ...mapMutations(["keepAliveDel"])
  }
};
</script>

你可能感兴趣的:(#,Vue)