search
HomeWeb Front-endJS TutorialDetailed examples of the use of keep-alive components of vue.js built-in components

keep-alive is a built-in component of Vue.js. This article mainly introduces the use of the keep-alive component of the built-in component of vue.js. Friends in need can refer to

keep-alive is a built-in component of Vue.js. When wrapping dynamic components, inactive component instances are cached instead of destroyed. It does not render a DOM element by itself, nor does it appear in the parent component chain. When a component is switched within , its two life cycle hook functions, activated and deactivated, will be executed accordingly. It provides two attributes, include and exclude, which allow components to be cached conditionally.

Give a chestnut

<keep-alive>
  <router-view v-if="$route.meta.keepAlive"></router-view>
 </keep-alive>
 <router-view v-if="!$route.meta.keepAlive"></router-view>

##When the button is clicked, the two inputs will switch, but At this time, the status of the two input boxes will be cached, and the content in the input tag will not disappear due to component switching.

* include - string or regular expression. Only matching components will be cached.

* exclude - string or regular expression. Any matching components will not be cached.

<keep-alive include="a">
 <component></component>
</keep-alive>

Only cache components whose component name is a

<keep-alive exclude="a">
 <component></component>
</keep-alive>

Except for the component with name a, everything else is cached

Life cycle hook

Life hook keep-alive provides two life hooks , respectively activated and deactivated.

Because keep-alive will save the component in the memory and will not destroy or recreate it, the created and other methods of the component will not be re-called. You need to use the two life hooks of activated and deactivated to know the current situation. Whether the component is active.

In-depth implementation of keep-alive component


View the vue--keep-alive component source code to get the following information

The created hook will create a cache object, which is used as a cache container to save vnode nodes.

props: {
 include: patternTypes,
 exclude: patternTypes,
 max: [String, Number]
},
created () {
 // 创建缓存对象
 this.cache = Object.create(null)
 // 创建一个key别名数组(组件name)
 this.keys = []
},

The destroyed hook clears all component instances in the cache when the component is destroyed.

destroyed () {
 /* 遍历销毁所有缓存的组件实例*/
 for (const key in this.cache) {
  pruneCacheEntry(this.cache, key, this.keys)
 }
},

:::demo


##
render () {
 /* 获取插槽 */
 const slot = this.$slots.default
 /* 根据插槽获取第一个组件组件 */
 const vnode: VNode = getFirstComponentChild(slot)
 const componentOptions: ?VNodeComponentOptions = vnode && vnode.componentOptions
 if (componentOptions) {
 // 获取组件的名称(是否设置了组件名称name,没有则返回组件标签名称)
 const name: ?string = getComponentName(componentOptions)
 // 解构对象赋值常量
 const { include, exclude } = this
 if ( /* name不在inlcude中或者在exlude中则直接返回vnode */
  // not included
  (include && (!name || !matches(include, name))) ||
  // excluded
  (exclude && name && matches(exclude, name))
 ) {
  return vnode
 }
 const { cache, keys } = this
 const key: ?string = vnode.key == null
  // same constructor may get registered as different local components
  // so cid alone is not enough (#3269)
  ? componentOptions.Ctor.cid + (componentOptions.tag ? `::${componentOptions.tag}` : &#39;&#39;)
  : vnode.key
 if (cache[key]) { // 判断当前是否有缓存,有则取缓存的实例,无则进行缓存
  vnode.componentInstance = cache[key].componentInstance
  // make current key freshest
  remove(keys, key)
  keys.push(key)
 } else {
  cache[key] = vnode
  keys.push(key)
  // 判断是否设置了最大缓存实例数量,超过则删除最老的数据,
  if (this.max && keys.length > parseInt(this.max)) {
  pruneCacheEntry(cache, keys[0], keys, this._vnode)
  }
 }
 // 给vnode打上缓存标记
 vnode.data.keepAlive = true
 }
 return vnode || (slot && slot[0])
}
// 销毁实例
function pruneCacheEntry (
 cache: VNodeCache,
 key: string,
 keys: Array<string>,
 current?: VNode
) {
 const cached = cache[key]
 if (cached && (!current || cached.tag !== current.tag)) {
 cached.componentInstance.$destroy()
 }
 cache[key] = null
 remove(keys, key)
}
// 缓存
function pruneCache (keepAliveInstance: any, filter: Function) {
 const { cache, keys, _vnode } = keepAliveInstance
 for (const key in cache) {
 const cachedNode: ?VNode = cache[key]
 if (cachedNode) {
  const name: ?string = getComponentName(cachedNode.componentOptions)
  // 组件name 不符合filler条件, 销毁实例,移除cahe
  if (name && !filter(name)) {
  pruneCacheEntry(cache, key, keys, _vnode)
  }
 }
 }
}
// 筛选过滤函数
function matches (pattern: string | RegExp | Array<string>, name: string): boolean {
 if (Array.isArray(pattern)) {
 return pattern.indexOf(name) > -1
 } else if (typeof pattern === &#39;string&#39;) {
 return pattern.split(&#39;,&#39;).indexOf(name) > -1
 } else if (isRegExp(pattern)) {
 return pattern.test(name)
 }
 /* istanbul ignore next */
 return false
}
// 检测 include 和 exclude 数据的变化,实时写入读取缓存或者删除
mounted () {
 this.$watch(&#39;include&#39;, val => {
 pruneCache(this, name => matches(val, name))
 })
 this.$watch(&#39;exclude&#39;, val => {
 pruneCache(this, name => !matches(val, name))
 })
},

:::

By looking at the Vue source code, we can see that keep-alive passes 3 attributes by default, include, exclude, max, max the maximum cacheable length

Combined with the source code, we can implement a router with configurable cache -view

<!--exclude - 字符串或正则表达式。任何匹配的组件都不会被缓存。-->
<!--TODO 匹配首先检查组件自身的 name 选项,如果 name 选项不可用,则匹配它的局部注册名称-->
<keep-alive :exclude="keepAliveConf.value">
 <router-view class="child-view" :key="$route.fullPath"></router-view>
</keep-alive>
<!-- 或者 -->
<keep-alive :include="keepAliveConf.value">
 <router-view class="child-view" :key="$route.fullPath"></router-view>
</keep-alive>
<!-- 具体使用 include 还是exclude 根据项目是否需要缓存的页面数量多少来决定-->

Create a keepAliveConf.js and place the component name that needs to match

// 路由组件命名集合
 var arr = [&#39;component1&#39;, &#39;component2&#39;];
 export default {value: routeList.join()};

Configure the global method of resetting the cache

import keepAliveConf from &#39;keepAliveConf.js&#39;
Vue.mixin({
 methods: {
 // 传入需要重置的组件名字
 resetKeepAive(name) {
  const conf = keepAliveConf.value;
  let arr = keepAliveConf.value.split(&#39;,&#39;);
  if (name && typeof name === &#39;string&#39;) {
   let i = arr.indexOf(name);
   if (i > -1) {
    arr.splice(i, 1);
    keepAliveConf.value = arr.join();
    setTimeout(() => {
     keepAliveConf.value = conf
    }, 500);
   }
  }
 },
 }
})

Call this.resetKeepAive(name) at the appropriate time to trigger keep-alive to destroy the component instance;

Vue.js internally abstracts DOM nodes into VNode nodes. The cache of the keep-alive component is also based on VNode nodes instead of directly storing the DOM structure. It caches the components that meet the conditions in the cache object, and then takes the vnode node out of the cache object and renders it when it needs to be re-rendered.

The above is the detailed content of Detailed examples of the use of keep-alive components of vue.js built-in components. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

The Origins of JavaScript: Exploring Its Implementation LanguageThe Origins of JavaScript: Exploring Its Implementation LanguageApr 29, 2025 am 12:51 AM

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

Behind the Scenes: What Language Powers JavaScript?Behind the Scenes: What Language Powers JavaScript?Apr 28, 2025 am 12:01 AM

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version