Vue3中keep-alive的使用及注意事項說明
更新時間:2025年04月17日 10:55:06 作者:大樊子
這篇文章主要介紹了Vue3中keep-alive的使用及注意事項說明,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
Vue3中keep-alive使用及注意事項
keep-alive 是 Vue 內置的一個抽象組件,用于緩存不活動的組件實例,避免重復渲染,提高性能。
以下是它的詳細用法和注意事項:
基本用法
<template>
<!-- 基本用法 -->
<keep-alive>
<component :is="currentComponent"></component>
</keep-alive>
<!-- 緩存特定組件 -->
<keep-alive include="CompA,CompB" exclude="CompC">
<router-view></router-view>
</keep-alive>
</template>主要功能
- 組件緩存:當組件切換時,保留組件狀態(tài)(如數(shù)據、滾動位置等)
- 避免重復渲染:減少不必要的 DOM 操作和生命周期鉤子執(zhí)行
- 保留狀態(tài):保持表單輸入內容、滾動位置等
核心屬性

生命周期鉤子
被 keep-alive 緩存的組件會觸發(fā)特有的生命周期鉤子:
onActivated:組件被激活時調用(進入緩存組件)onDeactivated:組件被停用時調用(離開緩存組件)
import { onActivated, onDeactivated } from 'vue'
export default {
setup() {
onActivated(() => {
console.log('組件被激活')
})
onDeactivated(() => {
console.log('組件被停用')
})
}
}與 Vue Router 結合使用
<template>
<keep-alive :include="cachedViews">
<router-view v-slot="{ Component }">
<transition name="fade">
<component :is="Component" />
</transition>
</router-view>
</keep-alive>
</template>
<script>
import { ref } from 'vue'
export default {
setup() {
const cachedViews = ref(['Home', 'User'])
return { cachedViews }
}
}
</script>注意事項
組件必須有 name 選項:include 和 exclude 匹配的是組件的 name 選項
動態(tài)組件切換問題:
- 使用
key屬性強制重新渲染:
<keep-alive><comp :key="id"></comp></keep-alive>
- 或者使用
v-if控制:
<comp v-if="show"></comp>
內存占用:
- 緩存過多組件可能導致內存占用過高
- 使用
max屬性限制緩存數(shù)量
數(shù)據更新時機:
- 緩存的組件不會重新創(chuàng)建,因此
created/mounted不會再次觸發(fā) - 應在
activated中處理數(shù)據刷新邏輯
滾動行為:
- 默認會保持滾動位置
- 如需重置滾動位置,可在
activated中處理:
onActivated(() => {
window.scrollTo(0, 0)
})與 Transition 一起使用:
<router-view v-slot="{ Component }">
<transition name="fade">
<keep-alive>
<component :is="Component" />
</keep-alive>
</transition>
</router-view>最佳實踐
- 只緩存必要的組件(如表單頁、列表頁)
- 對需要頻繁切換但狀態(tài)需要保留的組件使用
- 避免緩存大型組件或包含大量數(shù)據的組件
- 在路由元信息中管理緩存:
const routes = [
{
path: '/user',
component: User,
meta: { keepAlive: true }
}
]通過合理使用 keep-alive,可以顯著提升應用性能,特別是在移動端或需要頻繁切換視圖的場景中。
總結
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
vue-awesome-swiper 基于vue實現(xiàn)h5滑動翻頁效果【推薦】
說到h5的翻頁,很定第一時間想到的是swiper。但是我當時想到的卻是,vue里邊怎么用swiper。這篇文章主要介紹了vue-awesome-swiper - 基于vue實現(xiàn)h5滑動翻頁效果 ,需要的朋友可以參考下2018-11-11

