在Vue3中使用缓存组件keep-alive vue3缓存组件
在Vue3中使用缓存组件keep-alive vue3缓存组件
- 1、路由开启缓存
- 2、App.vue中使用 keep-alive
- 3、缓存组件激活 生命周期
- 3.1 组合式 语法风格
- 3.2 选项式 语法风格
1、路由开启缓存
const routes = [{path: '/',component: Home,meta: {keepAlive: true, // 设置需要缓存的组件},},{path: '/about',component: About,meta: {keepAlive: true, // 设置需要缓存的组件},},// 其他路由配置
];
2、App.vue中使用 keep-alive
keep-alive组件 在vue3中写法和vue2不一样
<template><div><!-- Vue3缓存组件,写法和Vue2不一样--><router-view v-slot="{ Component }"><!-- 使用 keep-alive 缓存组件 --><keep-alive><component :is="Component" /></keep-alive></router-view></div>
</template><style>
#app {text-align: center;color: var(--ep-text-color-primary);
}
</style>
3、缓存组件激活 生命周期
3.1 组合式 语法风格
<script>
export default {activated() {// 缓存组件在被激活时会进入这里},
};<script>
3.2 选项式 语法风格
<script setup>
import { onActivated} from 'vue'onActivated(() => {console.info('缓存组件重新激活')
})
</script>