1. Concept:
keep-alive
Is a built-in component of Vue, and when it wraps a dynamic component, it caches inactive component instances, which will not be destroyed.
2. Function:
Used to cache components, avoid loading the same components multiple times, reduce performance consumption, and improve user experience.
3. Attributes
- include: string or regular expression. Only matching components will be cached.
- exclude: string or regular expression. No matching components are cached.
4. Use scenarios
For example: if there is a list page and a details page, then the user may often execute the opening details => Return to list => Open details, and then the list component can be cached, so that every time the user returns to the list, he can quickly render from the cache instead of re-rendering the page, thereby saving memory overhead.
5. How to use:
5.1. Use inkeep-alive
Components to cache all pages
<div > <keep-alive> <header-bar></header-bar> <div class="container"> <menu></menu> <Main /> </div> <footer-bar></footer-bar> </keep-alive> </div>
5.2. Cache according to conditions, use include, exclude to determine whether to cache
5.2.1. Caches the component with name as keep. If there are multiple ones, you can use commas to divide it.
<keep-alive include='keep'> <router-view/> </keep-alive>
5.2.2. Components whose name is nokeeper will not be cached
<keep-alive exclude='nokeep'> <router-view/> </keep-alive>
5.2.3. You can also use attribute binding to dynamic judgment
<keep-alive :include='includedFun'> <router-view/> </keep-alive>
5.3. In the router directory,
5.3.1. Usemeta: { keepAlive = true }
, indicating that cache is required
const routes = [ { path: '/', component: Home }, { path:'/ login', component: Login }, { path: '/list', component: List, meta: { isKeep: true } }, { path: '/detail', component: Detail, meta:{ isKeep: true } } ]
5.3.2.Make judgment in
<div > <keep-alive> <router-view v-if="$"></router-view> </keep-alive> <router-view></router-view> </div>
What is the role of keep-alive in Vue? How to use it? That’s all for the article. For more related content on keep-alive in Vue, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!