Vue3中keep-alive的使用及注意事項(xiàng)說明
Vue3中keep-alive使用及注意事項(xiàng)
keep-alive 是 Vue 內(nèi)置的一個(gè)抽象組件,用于緩存不活動(dòng)的組件實(shí)例,避免重復(fù)渲染,提高性能。
以下是它的詳細(xì)用法和注意事項(xiàng):
基本用法
<template>
<!-- 基本用法 -->
<keep-alive>
<component :is="currentComponent"></component>
</keep-alive>
<!-- 緩存特定組件 -->
<keep-alive include="CompA,CompB" exclude="CompC">
<router-view></router-view>
</keep-alive>
</template>主要功能
- 組件緩存:當(dāng)組件切換時(shí),保留組件狀態(tài)(如數(shù)據(jù)、滾動(dòng)位置等)
- 避免重復(fù)渲染:減少不必要的 DOM 操作和生命周期鉤子執(zhí)行
- 保留狀態(tài):保持表單輸入內(nèi)容、滾動(dòng)位置等
核心屬性

生命周期鉤子
被 keep-alive 緩存的組件會(huì)觸發(fā)特有的生命周期鉤子:
onActivated:組件被激活時(shí)調(diào)用(進(jìn)入緩存組件)onDeactivated:組件被停用時(shí)調(diào)用(離開緩存組件)
import { onActivated, onDeactivated } from 'vue'
export default {
setup() {
onActivated(() => {
console.log('組件被激活')
})
onDeactivated(() => {
console.log('組件被停用')
})
}
}與 Vue Router 結(jié)合使用
<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>注意事項(xiàng)
組件必須有 name 選項(xiàng):include 和 exclude 匹配的是組件的 name 選項(xiàng)
動(dòng)態(tài)組件切換問題:
- 使用
key屬性強(qiáng)制重新渲染:
<keep-alive><comp :key="id"></comp></keep-alive>
- 或者使用
v-if控制:
<comp v-if="show"></comp>
內(nèi)存占用:
- 緩存過多組件可能導(dǎo)致內(nèi)存占用過高
- 使用
max屬性限制緩存數(shù)量
數(shù)據(jù)更新時(shí)機(jī):
- 緩存的組件不會(huì)重新創(chuàng)建,因此
created/mounted不會(huì)再次觸發(fā) - 應(yīng)在
activated中處理數(shù)據(jù)刷新邏輯
滾動(dòng)行為:
- 默認(rèn)會(huì)保持滾動(dòng)位置
- 如需重置滾動(dòng)位置,可在
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>最佳實(shí)踐
- 只緩存必要的組件(如表單頁、列表頁)
- 對(duì)需要頻繁切換但狀態(tài)需要保留的組件使用
- 避免緩存大型組件或包含大量數(shù)據(jù)的組件
- 在路由元信息中管理緩存:
const routes = [
{
path: '/user',
component: User,
meta: { keepAlive: true }
}
]通過合理使用 keep-alive,可以顯著提升應(yīng)用性能,特別是在移動(dòng)端或需要頻繁切換視圖的場(chǎng)景中。
總結(jié)
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
使用Vue做一個(gè)簡(jiǎn)單的todo應(yīng)用的三種方式的示例代碼
這篇文章主要介紹了使用Vue做一個(gè)簡(jiǎn)單的todo應(yīng)用的三種方式的示例代碼,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2018-10-10
VUE項(xiàng)目運(yùn)行失敗原因及解決辦法圖解(以vscode為例)
記錄一下踩坑,前幾天從同事手上接手了一個(gè)Vue的項(xiàng)目,下面這篇文章主要給大家介紹了關(guān)于VUE項(xiàng)目運(yùn)行失敗原因及解決辦法的相關(guān)資料,本文以vscode為例,需要的朋友可以參考下2023-06-06
Vue封裝數(shù)字框組件實(shí)現(xiàn)流程詳解
這篇文章主要介紹了Vue封裝數(shù)字框組件實(shí)現(xiàn)流程,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧2023-04-04
vue-awesome-swiper 基于vue實(shí)現(xiàn)h5滑動(dòng)翻頁效果【推薦】
說到h5的翻頁,很定第一時(shí)間想到的是swiper。但是我當(dāng)時(shí)想到的卻是,vue里邊怎么用swiper。這篇文章主要介紹了vue-awesome-swiper - 基于vue實(shí)現(xiàn)h5滑動(dòng)翻頁效果 ,需要的朋友可以參考下2018-11-11

