keep-alive router-view完美实现vue路由缓存vue组件缓存的方案 🔥🔥🔥

项目需求

部分路由页面需要被缓存,可以在特定时期取消缓存,比方说登陆过期

解决思路

  1. 利用keep-alive
  2. 结合vuex可以动态决定哪些路由页面(路由页面其实也是组件)需要被缓存

解决代码

1. 入口文件

<template>
  <div id="app">
    <keep-alive :include="$store.state.keepAliveList">
      <router-view />
    </keep-alive>
  </div>
</template>

2. vuex store

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    // 需要缓存的组件
    keepAliveList: [],
  },
  mutations: {},
  actions: {},
  modules: {}
})

3. 需要被缓存的页面代码


<template>
  <div>
  </div>
</template>

<script>
export default {
 // 起个规范的名字
  name:'data-check',
  components: {
  },
  data() {
    return {
    }
  },
  computed: {},
 // 初始化时像state增加自己,由于被缓存了,只会执行一次
  mounted() {
    this.$store.state.keepAliveList.push("data-check");
  },
  methods: {}
};
</script>
<style lang="scss" scoped>
</style>

4. 登录失效取消缓存

import Vue from "vue";

import axios from "axios";
import router from '../router'
import store from '../store'

Vue.prototype.$http = axios;

// Add a request interceptor
axios.interceptors.request.use(
  function (config) {
    // Do something before request is sent
    return config;
  },
  function (error) {
    // Do something with request error
    return Promise.reject(error);
  }
);

// Add a response interceptor
axios.interceptors.response.use(
  function (response) {
    console.log(response.data);
    if (response.data.status !== "1") {
      
      if (response.data.status === "10001" && response.data.message === "TOKEN信息没有提供") {
        store.state.keepAliveList = [];
      // 跳转到登录页
        router.replace({
          name: "bind"
        }).catch(() => {});
      } 
      }
    }
    // Any status code that lie within the range of 2xx cause this function to trigger
    // Do something with response data
    return response.data;
  },
  function (error) {
    // Any status codes that falls outside the range of 2xx cause this function to trigger
    // Do something with response error
    return Promise.reject(error);
  }
);
👍 码字不易,别忘点赞💖💖💖💖💖💖💖💖💖💖💖
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容