vue单页缓存组件

实现前进刷新,返回不刷新的功能,并且返回时可以记住上一页的滚动位置,有两套方案可选

第一套方案: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)
        }
      }

猜你喜欢

转载自www.cnblogs.com/afterwawa/p/9645996.html