vue3 watch 监听 清除store页面缓存
时间: 2025-02-15 15:05:41 浏览: 22
使用 Watch 监听并清除 Store 中的页面缓存
在 Vue3 中实现监听特定状态的变化来触发清除 store 中页面缓存的操作,可以采用 watch
来监视 Vuex store 或者 Pinia store(推荐用于 Vue3)的状态变化。当目标数据发生改变时,通过调用相应的方法来进行清理工作。
方法一:基于 Pinia Store 实现
Pinia 是官方推荐的新一代状态管理库,在 Vue3 应用中更为常用。假设有一个名为 useCacheStore
的 pinia store 负责管理页面缓存:
// stores/cache.js
import { defineStore } from 'pinia'
export const useCacheStore = defineStore('cache', {
state: () => ({
cachePages: []
}),
actions: {
clearPageCache(pageName) {
this.cachePages = this.cachePages.filter(name => name !== pageName);
}
}
})
接着可以在组件内使用如下方式设置监听器:
<template>
<!-- 组件模板 -->
</template>
<script setup>
import { ref, watch } from 'vue';
import { useRoute } from 'vue-router'
import { useCacheStore } from '@/stores/cache';
const route = useRoute();
const cacheStore = useCacheStore();
watch(() => route.fullPath, async (newVal, oldVal) => {
// 当路径发生变化时判断是否需要清空某些页面缓存
if (someConditionMet(newVal)) {
await cacheStore.clearPageCache('specific-page');
}
});
</script>
此代码片段展示了如何利用组合式 API (setup
) 函数内的 watch
功能监控路由对象(fullPath
)的变化,并据此决定何时以及哪个页面应该被移除其缓存[^1]。
方法二:直接操作 Vuex Store
如果项目仍然依赖于 Vuex,则可以通过类似的思路完成同样的功能。这里展示了一个简单的例子说明怎样定义一个 action 去更新缓存列表,并且在一个组件里边观察这个列表以便及时作出反应:
// store/index.js
import { createStore } from 'vuex'
export default createStore({
state: {
cachedViews: [],
},
mutations: {
CLEAR_CACHED_VIEW(state, viewName){
state.cachedViews = state.cachedViews.filter(v=>v!==viewName)
}
},
actions:{
clearCachedView({commit}, payload){
commit('CLEAR_CACHED_VIEW',payload)
}
}
})
// Component.vue
<template>
...
</template>
<script>
import { mapActions,mapState } from "vuex";
import { watchEffect } from "vue";
export default{
computed:mapState(['cachedViews']),
mounted(){
watchEffect(()=>{
let currentView = getCurrentView(); // 获取当前视图名称或其他标识符
if(shouldClearCache(currentView)){
this.clearCachedView(currentView);
}
})
},
methods:mapActions(['clearCachedView'])
}
</script>
上述代码实现了对 Vuex store 内部状态变更的有效追踪,并能够在满足条件的情况下自动执行清除指定页面缓存的动作[^2]。
相关推荐


















