1. 程式人生 > >vue單頁緩存組件

vue單頁緩存組件

頁緩存 current vue run eno 就會 問題 live gist

實現前進刷新,返回不刷新的功能,並且返回時可以記住上一頁的滾動位置,有兩套方案可選

第一套方案:vue的keep-alive組件,vue-router提供的scrollbeheavior API

keep-alive:可以實現把要緩存的組件渲染的vnode記到cache裏邊,當返回的時候用緩存裏邊的dom直接渲染,但是存在的問題是存儲vnode節點的key是name,也就是定義路由時組件對應的name,這就會導致同樣的path,不同參數的時候打開的是從cache裏邊拿到的vnode,很多業務場景都是根據參數來顯示不同內容,而keep-alive底層並沒有對此做擴展,可以看下keep-alive源碼:https://github.com/vuejs/vue/blob/dev/src/core/components/keep-alive.js,

 vnode.key就是路由裏邊定義的name,關於vnode的源碼裏可以看
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) } }

vue單頁緩存組件