Home Web Front-end JS Tutorial Detailed examples of the use of keep-alive components of vue.js built-in components

Detailed examples of the use of keep-alive components of vue.js built-in components

Jul 12, 2018 pm 02:02 PM
alive keep vue 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>
Copy after login

##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>
Copy after login

Only cache components whose component name is a

<keep-alive exclude="a">
 <component></component>
</keep-alive>
Copy after login

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 = []
},
Copy after login

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)
 }
},
Copy after login

:::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))
 })
},
Copy after login

:::

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 根据项目是否需要缓存的页面数量多少来决定-->
Copy after login

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()};
Copy after login

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);
   }
  }
 },
 }
})
Copy after login

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 of this Website
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

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to add functions to buttons for vue How to add functions to buttons for vue Apr 08, 2025 am 08:51 AM

You can add a function to the Vue button by binding the button in the HTML template to a method. Define the method and write function logic in the Vue instance.

How to reference js file with vue.js How to reference js file with vue.js Apr 07, 2025 pm 11:27 PM

There are three ways to refer to JS files in Vue.js: directly specify the path using the &lt;script&gt; tag;; dynamic import using the mounted() lifecycle hook; and importing through the Vuex state management library.

How to use bootstrap in vue How to use bootstrap in vue Apr 07, 2025 pm 11:33 PM

Using Bootstrap in Vue.js is divided into five steps: Install Bootstrap. Import Bootstrap in main.js. Use the Bootstrap component directly in the template. Optional: Custom style. Optional: Use plug-ins.

How to use watch in vue How to use watch in vue Apr 07, 2025 pm 11:36 PM

The watch option in Vue.js allows developers to listen for changes in specific data. When the data changes, watch triggers a callback function to perform update views or other tasks. Its configuration options include immediate, which specifies whether to execute a callback immediately, and deep, which specifies whether to recursively listen to changes to objects or arrays.

How to return to previous page by vue How to return to previous page by vue Apr 07, 2025 pm 11:30 PM

Vue.js has four methods to return to the previous page: $router.go(-1)$router.back() uses &lt;router-link to=&quot;/&quot; component window.history.back(), and the method selection depends on the scene.

Vue realizes marquee/text scrolling effect Vue realizes marquee/text scrolling effect Apr 07, 2025 pm 10:51 PM

Implement marquee/text scrolling effects in Vue, using CSS animations or third-party libraries. This article introduces how to use CSS animation: create scroll text and wrap text with &lt;div&gt;. Define CSS animations and set overflow: hidden, width, and animation. Define keyframes, set transform: translateX() at the beginning and end of the animation. Adjust animation properties such as duration, scroll speed, and direction.

How to query the version of vue How to query the version of vue Apr 07, 2025 pm 11:24 PM

You can query the Vue version by using Vue Devtools to view the Vue tab in the browser's console. Use npm to run the "npm list -g vue" command. Find the Vue item in the "dependencies" object of the package.json file. For Vue CLI projects, run the "vue --version" command. Check the version information in the &lt;script&gt; tag in the HTML file that refers to the Vue file.

How to use vue traversal How to use vue traversal Apr 07, 2025 pm 11:48 PM

There are three common methods for Vue.js to traverse arrays and objects: the v-for directive is used to traverse each element and render templates; the v-bind directive can be used with v-for to dynamically set attribute values ​​for each element; and the .map method can convert array elements into new arrays.

See all articles