vue3 keep-alive使用
时间: 2023-09-17 15:13:10 浏览: 54
Vue3 中的 `keep-alive` 组件可以缓存动态组件,避免频繁地销毁和创建组件,提高应用的性能。使用 `keep-alive` 组件的步骤如下:
1. 在需要缓存的组件外层添加 `keep-alive` 组件。
```html
<template>
<keep-alive>
<router-view />
</keep-alive>
</template>
```
2. 在需要缓存的组件上添加 `v-slot` 指令,并设置 `name` 属性。
```html
<template>
<div v-slot="{ Component }">
<transition>
<component :is="Component" />
</transition>
</div>
</template>
<script>
export default {
name: 'MyComponent',
created() {
console.log('MyComponent created');
},
destroyed() {
console.log('MyComponent destroyed');
},
};
</script>
```
在上面的代码中,我们定义了一个组件 `MyComponent`,并在组件中添加了 `created` 和 `destroyed` 钩子函数,用于在组件被创建和销毁时输出日志。
3. 在使用 `MyComponent` 的地方,添加 `keep-alive` 组件的 `include` 属性,并设置为 `MyComponent`。
```html
<template>
<div>
<button @click="toggle">Toggle Component</button>
<keep-alive :include="['MyComponent']">
<component :is="currentComponent" />
</keep-alive>
</div>
</template>
<script>
import MyComponent from './MyComponent.vue';
export default {
components: {
MyComponent,
},
data() {
return {
currentComponent: null,
};
},
methods: {
toggle() {
this.currentComponent = this.currentComponent === MyComponent ? null : MyComponent;
},
},
};
</script>
```
在上面的代码中,我们使用 `MyComponent` 组件,并且在组件外层添加了 `keep-alive` 组件,并设置了 `include` 属性,用于缓存 `MyComponent` 组件。
当我们点击按钮切换组件时,可以看到 `MyComponent` 组件在第一次被创建时输出日志,切换组件时不会再次被创建,而是被缓存起来了。当我们销毁 `MyComponent` 组件时,也会输出日志。
相关推荐
![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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)