解决指定多个页面keep-alive缓存的问题,清除缓存

1、app.js

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

2、store/index.js

import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
export default new Vuex.Store({
  state: {
    keepAliveList: ['segmentSetting'],//segmentSetting该页面可以写死的,根据自己的需求
  },
  mutations: {
    updateAliveList(state, { name, status }) {
      if (status) {
        state.keepAliveList.push(name);
      } else {
        const index = state.keepAliveList.indexOf(name);
        index >= 0 && state.keepAliveList.splice(index, 1);
      }
    }
  },
  actions: {
  },
  modules: {
  }
});

3、主页面(不用缓存页面)缓存的页面路由 let keepAliveRoute = ['/newBuildBatch', '/newBuild'];

  beforeRouteEnter(to, from, next) {
    console.log("获取数据====》",from);
    if(from.path !== '/'){//跟页面刷新
      const store = from.matched[0].instances.default.$store;
      console.log("beforeRouteEnter to, from======>",to, from);
      let keepAliveRoute = ['/newBuildBatch', '/newBuild'];
      //判断是否需要清除缓存
      keepAliveRoute.indexOf(from.path)!==-1? store.commit('updateAliveList', { name: from.name, status: false }):null;
    }
    next();
  },
  beforeRouteLeave(to, from, next) {
    console.log("beforeRouteLeave to, from====>",to, from);
    let keepAliveRoute = ['/newBuildBatch', '/newBuild'];
    //判断是否需要缓存
    keepAliveRoute.indexOf(to.path)!==-1? this.$store.commit('updateAliveList', { name: to.name, status: true }): null;
    next();
  },

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Vue3中,可以通过使用`<keep-alive>`组件的`include`和`exclude`属性来控制哪些组件需要被缓存,哪些组件需要被清除缓存。 - `include`属性允许您指定哪些组件应该被缓存,可以是一个字符串或一个正则表达式。如果`include`属性被省略,则所有组件都将被缓存。 - `exclude`属性允许您指定哪些组件不应该被缓存,可以是一个字符串或一个正则表达式。 为了清除指定缓存,可以通过在组件中使用`<keep-alive>`的`exclude`属性来排除需要清除缓存的组件,然后通过修改该组件的`key`属性来强制重新渲染该组件,从而清除该组件的缓存。 例如,假设需要清除一个名为`MyComponent`的组件的缓存,可以在该组件中使用以下代码: ```html <template> <div :key="componentKey"> <!-- 组件内容 --> </div> </template> <script> export default { data() { return { componentKey: 0 } }, mounted() { // 在mounted钩子中修改组件的key属性来强制重新渲染 this.componentKey += 1 }, // 在组件中排除自身不被缓存 // 也可以使用字符串来排除:exclude="MyComponent" // 如果需要排除多个组件,可以使用正则表达式来匹配 // exclude="/(MyComponent|OtherComponent)/" // 如果需要缓存多个组件,可以使用include属性来指定 // include="/(MyComponent|OtherComponent)/" beforeRouteLeave(to, from, next) { if (to.name === 'home') { // 清除缓存,重新渲染组件 this.componentKey += 1 } next() } } </script> ``` 在上面的例子中,使用`componentKey`作为组件的`key`属性,当组件需要重新渲染时,修改该属性的值即可。在`beforeRouteLeave`钩子中,当用户离开该组件并进入名为`home`的路由时,清除该组件的缓存,重新渲染组件。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值