項目需求
部分路由頁面需要被緩存,可以在特定時期取消緩存裸删,比方說登陸過期
解決思路
- 利用keep-alive
- 結合vuex可以動態(tài)決定哪些路由頁面(路由頁面其實也是組件)需要被緩存
解決代碼
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 {
// 起個規(guī)范的名字
name:'data-check',
components: {
},
data() {
return {
}
},
computed: {},
// 初始化時像state增加自己暴匠,由于被緩存了,只會執(zhí)行一次
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);
}
);
?? 碼字不易卜高,別忘點贊??????????????????????