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.
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>
* 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>
<keep-alive exclude="a"> <component></component> </keep-alive>
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
props: { include: patternTypes, exclude: patternTypes, max: [String, Number] }, created () { // 创建缓存对象 this.cache = Object.create(null) // 创建一个key别名数组(组件name) this.keys = [] },
destroyed () { /* 遍历销毁所有缓存的组件实例*/ for (const key in this.cache) { pruneCacheEntry(this.cache, key, this.keys) } },
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}` : '') : 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 === 'string') { return pattern.split(',').indexOf(name) > -1 } else if (isRegExp(pattern)) { return pattern.test(name) } /* istanbul ignore next */ return false } // 检测 include 和 exclude 数据的变化,实时写入读取缓存或者删除 mounted () { this.$watch('include', val => { pruneCache(this, name => matches(val, name)) }) this.$watch('exclude', 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 = ['component1', 'component2']; export default {value: routeList.join()};
Configure the global method of resetting the cache
import keepAliveConf from 'keepAliveConf.js' Vue.mixin({ methods: { // 传入需要重置的组件名字 resetKeepAive(name) { const conf = keepAliveConf.value; let arr = keepAliveConf.value.split(','); if (name && typeof name === 'string') { 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!