項目中要求針對某個頁面需要添加緩存,於是用到了keep-alive,代碼如下:
<keep-alive> <div class="pages"> <router-view v-if="$route.meta.keepAlive" /> </div> </keep-alive> <router-view v-if="!$route.meta.keepAlive" /> 路由配置如下: { path: '/orderTable/:id', component: orderTable, name: 'orderTable', meta: { keepAlive: true // 是否緩存組件 } },
怎末看都不像有問題的樣子,但是二次路由切換到orderTable頁面時就是不生效,
如果是keep-alive緩存的組件就會有activated
和 deactivated 兩個鈎子函數,當再次進入緩存的組件頁面時,便觸發
activated和deactivated函數,不會再觸發created和mounted,於是在activated函數里面打斷點,當切回時並未進入該函數,說明keep-alive緩存的並不是一個組件,於是順這個方向查看了源碼如下:
........
render () {
const slot = this.$slots.default
const vnode: VNode = getFirstComponentChild(slot) // 獲取第一個節點元素
const componentOptions: ?VNodeComponentOptions = vnode && vnode.componentOptions // 判斷當前的vnode是不是組件
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
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)
// prune oldest entry
if (this.max && keys.length > parseInt(this.max)) {
pruneCacheEntry(cache, keys[0], keys, this._vnode)
}
}
vnode.data.keepAlive = true
}
return vnode || (slot && slot[0])
}
是不是一下就頓悟了,對於keep-alive緩存的組件,首先會讀取第一個節點,然后判斷它是不是一個組件,很顯然我們在router-view外套了div,對於div它不是一個組件,所以也執行不了接下來的代碼,只是將頁面渲染了出來而已。
記錄一下,謹防再犯,寫的不足之處,還望指教