vue代码实现清除缓存
Vue 中清除缓存的实现方法
方法一:使用 localStorage 或 sessionStorage
// 清除 localStorage
localStorage.clear();
// 清除 sessionStorage
sessionStorage.clear();
// 清除特定键值
localStorage.removeItem('keyName');
sessionStorage.removeItem('keyName');
方法二:清除 Vuex 状态
// 重置 Vuex store 为初始状态
store.replaceState({});
// 清除特定模块状态
store.commit('moduleName/RESET_STATE');
方法三:强制组件重新渲染
// 使用 v-if 强制重新挂载组件
<template>
<child-component v-if="showComponent" />
</template>
<script>
export default {
data() {
return {
showComponent: true
}
},
methods: {
refreshComponent() {
this.showComponent = false;
this.$nextTick(() => {
this.showComponent = true;
});
}
}
}
</script>
方法四:清除路由缓存
// 在 router-view 上使用 key 属性
<router-view :key="$route.fullPath" />
// 或者在路由守卫中处理
router.beforeEach((to, from, next) => {
if (to.meta.noCache) {
to.matched.forEach(record => {
record.components.default = null;
});
}
next();
});
方法五:清除 axios 缓存
// 在 axios 请求中添加时间戳参数
axios.get('/api/data', {
params: {
timestamp: new Date().getTime()
}
});
// 或者全局配置
axios.interceptors.request.use(config => {
if (config.method === 'get') {
config.params = {
...config.params,
_: new Date().getTime()
}
}
return config;
});
方法六:清除 Service Worker 缓存
// 注销所有 Service Worker
if ('serviceWorker' in navigator) {
navigator.serviceWorker.getRegistrations().then(registrations => {
registrations.forEach(registration => {
registration.unregister();
});
});
}
// 清除特定缓存
caches.keys().then(cacheNames => {
return Promise.all(
cacheNames.map(cacheName => {
return caches.delete(cacheName);
})
);
});
方法七:使用 keep-alive 排除缓存
// 在 keep-alive 中使用 exclude 属性
<keep-alive exclude="ComponentName">
<router-view></router-view>
</keep-alive>
// 或者在组件内部处理
export default {
name: 'ComponentName',
activated() {
// 组件激活时刷新数据
this.fetchData();
}
}
选择适合项目需求的清除缓存方法,根据实际场景组合使用效果更佳。






