Preface
keep-alive is a built-in component of Vue that when it wraps dynamic components, it caches inactive component instances instead of destroying them. For example: In development, you often need to cache the status of the list page (such as scrolling position information) when jumping from a list to a detail page. At this time, you need to save the status and cache the status. Status is retained in memory during component switching, preventing repeated rendering of DOM, reducing loading time and performance consumption, and improving user experience. How to use it
<keep-alive> <component /> </keep-alive>
The component here will be cached.
1. Concept:
keep-alive is a built-in component of Vue that caches inactive component instances instead of being destroyed when it wraps dynamic components.
2. Function:
Used to cache components, avoid loading the same components multiple times, reduce performance consumption, and improve user experience.
3. How to use:
Method 1: Use keep-alive tag in it to cache all pages
<div > <keep-alive> <tar-bar></tar-bar> <div class="container"> <left-menu></left-menu> <Main /> </div> </keep-alive> </div>
Method 2: Cache according to the conditions, use include, exclude to determine whether to cache
// 1. Cache the component with name cc. If there are multiple ones, you can use commas to divide it. <keep-alive include='cc'> <router-view/> </keep-alive> // 2. Components whose name is cc will not be cached <keep-alive exclude='cc'> <router-view/> </keep-alive> // 3. You can also use attribute binding to dynamic judgment <keep-alive :include='includedComs'> <router-view/> </keep-alive>
Method 3: In the router directory,
Step 1: Use meta:{keepAlive = true}, indicating that cache is required
const routes = [ { path:'/', component:Home, meta:{ keepalive:true } }, { path:'/login', component:Login }, { path:'/edit', component:Edit, meta:{ istoken: true } }, { path:'/home', component:Home, meta:{ keepalive:true } } ]
- Step 2: Make judgments in
<div > <!--keep-alive It means that the page will not be destroyed,Keep the page state--> <keep-alive> <router-view v-if="$"></router-view> </keep-alive> <router-view v-if="!$"></router-view> </div>
This is the end of this article about the detailed explanation of the use of keep-alive in Vue. For more related content on Vue keep-alive, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!