父子组件切换使用keep-alive暂时缓存数据,离开父子组价时重新渲染
时间: 2024-01-07 22:14:55 浏览: 33
在 Vue 中,使用 `keep-alive` 组件可以将组件缓存起来,当组件被切换时,不会重新渲染,而是从缓存中读取。如果需要在离开组件时清除缓存,可以使用 `deactivated` 生命周期钩子函数。下面是一个示例:
```vue
<template>
<div>
<div v-if="showParent">
<h2>Parent Component</h2>
<button @click="toggle">Toggle Child Component</button>
<keep-alive>
<component :is="currentComponent">
</component>
</keep-alive>
</div>
<div v-else>
<h2>Other Component</h2>
<button @click="showParent = true">Back to Parent Component</button>
</div>
</div>
</template>
<script>
import ChildComponentA from './ChildComponentA.vue';
import ChildComponentB from './ChildComponentB.vue';
export default {
components: {
ChildComponentA,
ChildComponentB
},
data() {
return {
showParent: true,
currentComponent: 'ChildComponentA'
};
},
methods: {
toggle() {
this.currentComponent = this.currentComponent === 'ChildComponentA' ? 'ChildComponentB' : 'ChildComponentA';
}
},
deactivated() {
// 离开组件时清除缓存
this.$options.components.ChildComponentA.__patch__(null, null, true);
this.$options.components.ChildComponentB.__patch__(null, null, true);
}
};
</script>
```
在这个例子中,我们使用 `keep-alive` 包裹了一个动态组件,然后在父组件中切换两个不同的子组件。当我们离开父组件时,会触发 `deactivated` 生命周期钩子函数,这里我们手动清除了子组件的缓存,这样下次进入父组件时,子组件会重新渲染。注意,在清除缓存时应该传入第三个参数 `true`,以确保子组件的状态也被清除。
需要注意的是,使用 `keep-alive` 组件缓存组件时,被缓存的组件会保留它们的状态和数据。如果需要在缓存后重新渲染组件时重置状态和数据,可以使用 `activated` 和 `deactivated` 生命周期钩子函数。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)