keep-alive
是Vue提供的一个抽象组件,用来对组件进行缓存,从而节省性能,由于是一个抽象组件,所以在vue页面渲染完毕后不会被渲染成一个DOM元素,使用keep-alive包裹动态组件时,会缓存不活动的组件实例,而不是销毁它们
动态代码如下:
<keep-alive :include="cachedView"> <router-view :key="key" /> </keep-alive>
// src/core/components/keep-alive.js
export default { name: ‘keep-alive‘, abstract: true, // 判断当前组件虚拟dom是否渲染成真实dom的关键 props: { include: patternTypes, // 缓存白名单 exclude: patternTypes, // 缓存黑名单 max: [String, Number] // 缓存的组件 }, created() { this.cache = Object.create(null) // 缓存虚拟dom this.keys = [] // 缓存的虚拟dom的键集合 }, destroyed() { for (const key in this.cache) { // 删除所有的缓存 pruneCacheEntry(this.cache, key, this.keys) } }, mounted() { // 实时监听黑白名单的变动 this.$watch(‘include‘, val => { pruneCache(this, name => matched(val, name)) }) this.$watch(‘exclude‘, val => { pruneCache(this, name => !matches(val, name)) }) }, render() { // 先省略... } }
function pruneCacheEntry ( cache: VNodeCache, key: string, keys: Array<string>, current?: VNode ) { const cached = cache[key] if (cached && (!current || cached.tag !== current.tag)) { cached.componentInstance.$destroyed() // 执行组件的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) if (name && !filter(name)) { pruneCacheEntry(cache, key, keys, _vnode) } } } }
render () { const slot = this.$slots.defalut const vnode: VNode = getFirstComponentChild(slot) // 找到第一个子组件对象 const componentOptions : ?VNodeComponentOptions = vnode && vnode.componentOptions if (componentOptions) { // 存在组件参数 // check pattern const name: ?string = getComponentName(componentOptions) // 组件名 const { include, exclude } = this if (// 条件匹配 // not included (include && (!name || !matches(include, name)))|| // excluded (exclude && name && matches(exclude, name)) ) { return vnode } const { cache, keys } = this // 定义组件的缓存key const key: ?string = vnode.key === null ? componentOptions.Ctor.cid + (componentOptions.tag ? ‘::${componentOptions.tag}‘ : ‘‘) : vnode.key if (cache[key]) { // 已经缓存过该组件 vnode.componentInstance = cache[key].componentInstance remove(keys, key) keys.push(key) // 调整key排序 } else { cache[key] = vnode //缓存组件对象 keys.push(key) if (this.max && keys.length > parseInt(this.max)) { //超过缓存数限制,将第一个删除 pruneCacheEntry(cahce, keys[0], keys, this._vnode) } } vnode.data.keepAlive = true //渲染和执行被包裹组件的钩子函数需要用到 } return vnode || (slot && slot[0]) }
import App from ‘./App.vue‘ new Vue({ render: h => h(App) }).$mount(‘#app‘)
export function initLifecycle (vm: Component) { const options= vm.$options // 找到第一个非abstract父组件实例 let parent = options.parent if (parent && !options.abstract) { while (parent.$options.abstract && parent.$parent) { parent = parent.$parent } parent.$children.push(vm) } vm.$parent = parent // ... }
最后构建的组件树中就不会包含keep-alive组件,那么由组件树渲染成的DOM树自然也不会有keep-alive相关的节点了
// src/core/vdom/patch.js function createComponent (vnode, insertedVnodeQueue, parentElm, refElm) { let i = vnode.data if (isDef(i)) { const isReactivated = isDef(vnode.componentInstance) && i.keepAlive if (isDef(i = i.hook) && isDef(i = i.init)) { i(vnode, false) } if (isDef(vnode.componentInstance)) { initComponent(vnode, insertedVnodeQueue) insert(parentElem, vnode.elem, refElem) // 将缓存的DOM(vnode.elem) 插入父元素中 if (isTrue(isReactivated)) { reactivateComponent(vnode, insertedVnodeQueue, parentEle, refElm) } return true } } }
在首次加载被包裹组建时,由keep-alive.js中的render函数可知,vnode.componentInstance的值是undfined,keepAlive的值是true,因为keep-alive组件作为父组件,它的render函数会先于被包裹组件执行;那么只执行到i(vnode,false),后面的逻辑不执行;
再次访问被包裹组件时,vnode.componentInstance的值就是已经缓存的组件实例,那么会执行insert(parentElm, vnode.elm, refElm)逻辑,这样就直接把上一次的DOM插入到父元素中。
5. 不可忽视:钩子函数
// src/core/vdom/create-component.js const componentVNodeHooks = { init (vnode: VNodeWithData, hydrating: boolean): ?boolean{ if ( vnode.componentInstance && !vnode.componentInstance._isDestroyed && vnode.data.keepAlive ) { // keep-alive components, treat as a patch const mountedNode:any = vnode componentVNodeHooks.prepatch(mountedNode, mountedNode) } else { const child = vnode.componentInstance = createComponentInstanceForVnode (vnode, activeInstance) } } }
// src/core/vdom/patch.js function invokeInsertHook (vnode, queue, initial) { if (isTrue(initial) && isDef(vnode.parent)) { vnode.parent.data,pendingInsert = queue } else { for(let i =0; i<queue.length; ++i) { queue[i].data.hook.insert(queue[i]) // 调用VNode自身的insert钩子函数 } } }
const componentVNodeHooks = { // init() insert (vnode: MountedComponentVNode) { const { context, componentInstance } = vnode if (!componentInstance._isMounted) { componentInstance._isMounted = true callHook(componentInstance, ‘mounted‘) } if (vnode.data.keepAlive) { if (context._isMounted) { queueActivatedComponent(componentInstance) } else { activateChildComponent(componentInstance, true/* direct */) } } } }
// src/core/instance/lifecycle.js export function activateChildComponent (vm: Component, direct?: boolean) { if (direct) { vm._directInactive = false if (isInInactiveTree(vm)) { return } } else if (vm._directInactive) { return } if (vm._inactive || vm._inactive === null) { vm._inactive = false for (let i = 0; i < vm.$children.length; i++) { activateChildComponent(vm.$children[i]) } callHook(vm, ‘activated‘) } }
--转自作者:amCow 链接:[https://www.jianshu.com/p/9523bb439950]。
router-view的key属性
这个key的作用:
从/page?id=1 => /page?id=2, 由于这两个路由的$route.path一样, 所以和没设置 key 属性一样, 会复用组件, 相关钩子加载顺序为:
beforeRouteUpdate
3. 设置 router-view 的 key 属性值为 $route.fullPath
从/page/1 => /page/2, 由于这两个路由的$route.fullPath并不一样, 所以组件被强制不复用, 相关钩子加载顺序为:
beforeRouteUpdate => created => mounted
从/page?id=1 => /page?id=2, 由于这两个路由的$route.fullPath并不一样, 所以组件被强制不复用, 相关钩子加载顺序为:
beforeRouteUpdate => created => mounted
vue的keep-alive的页面缓存机制和router-view的key作用
原文:https://www.cnblogs.com/yan-975-yy/p/13878162.html