vue 使某个组件不被 keep-alive 缓存
时间: 2023-08-29 13:07:02 浏览: 59
可以在组件标签上加上一个属性,比如 `no-cache`,然后在 `keep-alive` 组件的 `exclude` 属性中排除这个组件。
示例代码:
```vue
<template>
<div>
<keep-alive :exclude="excludeComponents">
<router-view></router-view>
</keep-alive>
</div>
</template>
<script>
export default {
data() {
return {
excludeComponents: []
};
},
created() {
this.$router.beforeEach((to, from, next) => {
const exclude = to.matched.some(record => record.meta.noCache);
if (exclude) {
this.excludeComponents.push(to.name);
} else {
const index = this.excludeComponents.indexOf(to.name);
if (index !== -1) {
this.excludeComponents.splice(index, 1);
}
}
next();
});
}
};
</script>
```
在需要禁用缓存的组件中,添加 `noCache: true` 的 meta 信息:
```javascript
{
path: '/example',
name: 'Example',
component: Example,
meta: {
noCache: true
}
}
```
然后在组件标签上添加 `no-cache` 属性即可:
```vue
<template>
<div v-if="!$route.meta.noCache">
<!-- 不禁用缓存的代码 -->
</div>
<div v-else>
<!-- 禁用缓存的代码 -->
</div>
</template>
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)