vue——取消keepAlive缓存

635 阅读3分钟

携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第29天,点击查看活动详情

keepalive可以用来对vue组件进行缓存,之前的文章中我们也讲到了如何使用keepalive,但一旦组件使用了keepalive,那么keepalive缓存便一直存在,但如果我们从另一个页面进入,我们肯定不想保留之前其他来源的缓存,所以要在适当的时机清除keepalive。

keepalive:include属性

include属性表示组件名字的集合,只要组件名字在keepalive的include属性当中,那么此组件就可以被缓存。所以,我们可以通过维护include属性的值,在适当的时机对组件增加或取消keepalive缓存

实现

1、缓存页面的维护

我们将需要添加keepalive的页面名称维护在store中的includePages数组当中,另外添加两个维护此数组的方法,一个是addPage方法,用来添加需要使用缓存的页面名字;一个是deletePage方法,用来取消之前添加过的keepalive缓存,代码如下:

const store = createStore({
  state: {
    includePages: ['']
  },
  mutations: {
    addPage(state, data) {
      if (!state.includePages.includes(data)) {
        state.includePages.push(data)
      }
    },
    deletePage(state, data) {
      const index = state.includePages.findIndex(item => item === data)
      state.includePages.splice(index, 1)
    }
  }
})

2、keepalive添加include属性

上面在store中维护了需要缓存的页面之后,我们可以直接从store中获取includePages属性,然后将includePages属性的值作为keepalive的include属性,这样当includePages属性的值发生变化时,keepalive中的inclue的页面也将发生变化,这样如果我们在某一时机需要取消keepalive缓存,那么直接store更改includePages即可,代码如下:

<router-view v-slot="{ Component }">
  <keep-alive :include="include">
    <component :is="Component" />
  </keep-alive>
</router-view>
  
<script setup lang="ts">
const include = computed(() => store.state.includePages)
</script>

3、添加及取消keepalive时机

假如有三个页面A、B、C,A页面可以跳转B页面,B页面可以跳转C页面,因为B页面中含有表单元素,所以当从B跳转C,然后又从C返回到B时,我们希望B页面中的表单数据能够保留,而不是要重新填,所以在这种情况下,我们就需要给B页面增加keepalive缓存。

当将B页面添加了keepalive缓存,然后我们从B返回A,然后再次进入B页面时,我们希望B能够展示新的状态,而不是之前的缓存,那么这种情况下,在B返回到A时,我们就需要清除keepalive缓存。

首先我们在进入B页面时,需要将B加入到store中维护的includePages数组中,可以在beforeEach方法中判断是否要进入B页面,如下:

router.beforeEach((to, from, next) => {
  if (to.name === ‘B’) {
    store.commit('addPage', 'B')
  }
  next()
})

然后就是取消B页面的keepalive缓存时机,我们希望,只有从C返回到B时,能保留B中的表单数据,其余情况进入B时,均不要缓存,而是展示最新的数据。所以,我们就可以在B页面中的onBeforeRouteLeave方法中进行判断,如果to不是C页面,那么就可以删除keepalive缓存,如下:

onBeforeRouteLeave((to) => {
  if (to.name !== 'C') {
    store.commit('deletePage', 'B')
  }
})

注意,取消keepalive缓存的时机,可以根据业务需求来进行调整。