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

无忌哥哥
无忌哥哥Original
2018-07-12 14:02:451794browse

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. 7c9485ff8c3cba5ae9343ed63c2dc3f7 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 7c9485ff8c3cba5ae9343ed63c2dc3f7, 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