Using <keep-alive> in Vue can preserve the status of component switching. 1. Enable cache by wrapping dynamic components in the <keep-alive> tag; 2. Use include and exclude attributes to control the cache range; 3. Components need to define the name attribute and use it with v-if; 4. The cache component will trigger the activated and deactivated life cycle hooks; 5. Applicable to Tab switching, form wizard, search and details pages and other scenarios, but excessive use should be avoided to avoid affecting performance.
In Vue development, if you want components to retain state when switching (such as form input, scroll position, etc.), <keep-alive></keep-alive>
is a very practical built-in component. It allows dynamic components to be not destroyed during switching, thus enabling state cache.

Basic usage: How to use <keep-alive></keep-alive>
You just need to wrap the components that need to be cached in the <keep-alive></keep-alive>
tag:

<keep-alive> <component :is="currentComponent" /> </keep-alive>
currentComponent
here is a dynamic component, such as switching different contents displayed through tabs. Once wrapped in <keep-alive>
, these components are not recreated and destroyed when switching, but instead enter a "cache" state.
Control cache: use of include and exclude
Sometimes we don't want to cache all components. At this time, we can use include
and exclude
attributes to control which components need to be cached.

-
include
: Only cache matching component names -
exclude
: Exclude specified components without cache
For example:
<keep-alive> <component :is="currentComponent" v-if="currentComponent" /> </keep-alive>
Set name
attribute in the component definition so that <keep-alive>
can recognize:
export default { name: 'UserProfile' }
You can write this way:
<keep-alive> <component :is="currentComponent" v-if="currentComponent" /> </keep-alive>
Note:
v-if
is required because<keep-alive>
has no effect onv-show
.
Lifecycle hook changes: activated and deactivated
When the component is cached by <keep-alive>
, its created
and mounted
will only be executed once. After that, every time you switch back, the activated
hook will be triggered; deactivated
when leaving.
You can do some cleaning or recovery operations in these two hooks:
export default { activated() { console.log('Component is activated'); }, deactivated() { console.log('Component is cached'); } }
Common uses include:
- Refetch data in
activated
(if needed) - Clear timer, cancel listening events, etc. in
deactivated
Scenario recommendations
Some typical scenarios suitable for using <keep-alive></keep-alive>
include:
- Tab switch pages, such as different subpages in the user center
- Form Wizard steps to avoid losing input when switching steps
- Jump between search result page details pages to keep search conditions unchanged
But be careful not to abuse it, because too many components will affect performance. It is recommended to selectively cache key components based on actual needs.
Basically that's it. Rational use of <keep-alive></keep-alive>
can significantly improve the user experience, especially in scenarios where components need to be switched frequently.
The above is the detailed content of Vue Keep-Alive Component for State Preservation. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

ToimplementdarkmodeinCSSeffectively,useCSSvariablesforthemecolors,detectsystempreferenceswithprefers-color-scheme,addamanualtogglebutton,andhandleimagesandbackgroundsthoughtfully.1.DefineCSSvariablesforlightanddarkthemestomanagecolorsefficiently.2.Us

Vertical centering content can be implemented in CSS in a variety of ways, the most direct way is to use Flexbox. 1. Use Flexbox: By setting the container to display:flex and in conjunction with align-items:center, vertical centering of child elements can be easily achieved; 2. Combination of absolute positioning and transform: suitable for absolute positioning elements, by setting top and left to 50% and then using translate (-50%,-50%) to achieve centering; 3. CSSGrid: Through display:grid and place-items:center, horizontal and vertical centering can be achieved at the same time. If only vertical centering is required, use align

The topic differencebetweenem, Rem, PX, andViewportunits (VH, VW) LiesintheirreFerencepoint: PXISFixedandbasedonpixelvalues, emissrelative EtothefontsizeFheelementoritsparent, Remisrelelatotherootfontsize, AndVH/VwarebaseDontheviewporttimensions.1.PXoffersprecis

CSSGridisapowerfultoolforcreatingcomplextwo-dimensionallayoutsbyofferingcontroloverbothrowsandcolumns.1.Itallowsexplicitdefinitionofrowsandcolumnswithflexiblesizingusingfeatureslikegrid-template-columns:repeat(auto-fit,minmax(200px,1fr))forresponsive

Choosing the correct display value in CSS is crucial because it controls the behavior of elements in the layout. 1.inline: Make elements flow like text, without occupying a single line, and cannot directly set width and height, suitable for elements in text, such as; 2.block: Make elements exclusively occupy one line and occupy all width, can set width and height and inner and outer margins, suitable for structured elements, such as; 3.inline-block: has both block characteristics and inline layout, can set size but still display in the same line, suitable for horizontal layouts that require consistent spacing; 4.flex: Modern layout mode, suitable for containers, easy to achieve alignment and distribution through justify-content, align-items and other attributes, yes

CSSHoudini is a set of APIs that allow developers to directly manipulate and extend the browser's style processing flow through JavaScript. 1. PaintWorklet controls element drawing; 2. LayoutWorklet custom layout logic; 3. AnimationWorklet implements high-performance animation; 4. Parser&TypedOM efficiently operates CSS properties; 5. Properties&ValuesAPI registers custom properties; 6. FontMetricsAPI obtains font information. It allows developers to expand CSS in unprecedented ways, achieve effects such as wave backgrounds, and have good performance and flexibility

ReactivitytransforminVue3aimedtosimplifyhandlingreactivedatabyautomaticallytrackingandmanagingreactivitywithoutrequiringmanualref()or.valueusage.Itsoughttoreduceboilerplateandimprovecodereadabilitybytreatingvariableslikeletandconstasautomaticallyreac

CSSgradientsenhancebackgroundswithdepthandvisualappeal.1.Startwithlineargradientsforsmoothcolortransitionsalongaline,specifyingdirectionandcolorstops.2.Useradialgradientsforcirculareffects,adjustingshapeandcenterposition.3.Layermultiplegradientstocre
