修改vue源码实现动态路由缓存javascript
即若是你有一个盘点录入单路由,但你想经过不一样的传不一样的ID来加载CheckInputInfo这个组件,若采用params方式,这时只须要在path后面配置/:taskId便可实现CheckInputInfo/1和CheckInputInfo/2这样的路由,同时能够经过this.$route.params.taskId来获取当前路由的taskId。php
{
path: 'CheckInputInfo/:taskId',
meta: {
title: '盘点录入单'
},
name: 'CheckInputInfo',
component: () => import('@/view/Check/CheckInputInfo.vue')
}
复制代码
相似的,一样也可以使用query方式,这时只须要在path后面配置:taskId便可实现CheckInputInfo?taskId=1和CheckInputInfo?taskId=2这样的路由,同时能够经过this.$route.query.taskId来获取当前路由的taskId。html
{
path: 'CheckInputInfo:taskId',
meta: {
title: '盘点录入单'
},
name: 'CheckInputInfo',
component: () => import('@/view/Check/CheckInputInfo.vue')
}
复制代码
vue-router经过配置params和query来实现动态路由,并可经过this.$route.xx来获取当前的params或query,省去了直接操做或处理window.location,仍是挺方便的。vue
解读:在不使用keep-alive的状况下,咱们每次加载路由,这时会从新render当前路由挂载的component,但若这两个路由是同一个路由组件配置的动态路由,vue为了性能设计了不会从新render。java
这显然不符合咱们的预期,那么该如何在动态路由下拥有完整的生命周期呢?答案是keep-alive。node
keep-alive经过缓存Vnode的方式解决了SPA最为关键的性能问题。如下,我就按步骤来分析如下:ios
<router-view></router-view>
复制代码
每次切换都会从新render,执行整个生命周期,每次切换时,从新render,从新请求,,必然不知足需求。git
<keep-alive>
<router-view></router-view>
</keep-alive>
复制代码
只是在进入当前路由的第一次render,来回切换不会从新执行生命周期,且能缓存router-view的数据。github
keep-alive采用render函数来建立Vnode,一下是vue v2.5.10的keep-alive.js的render():web
render () {
const slot = this.$slots.default
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
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])
}
}
复制代码
在render是获取到Vnode,若cache[key]存在,则:
vnode.componentInstance = cache[key].componentInstance
复制代码
不然,将Vnode保存在cache里:
cache[key] = vnode
复制代码
因而当时用keep-alive时,咱们就能够保存每一个route-view的数据。
最开始实际上是不知道这个bug的,也是经过现象反推,而后由源码解决这个问题的,那就先从现象提及:
动态路由缓存的的具体表如今:
- 由动态路由配置的路由只能缓存一份数据。
- keep-alive动态路由只有第一个会有完整的生命周期,以后的路由只会触发 actived 和 deactivated这两个钩子。
- 一旦更改动态路由的某个路由数据,期全部同路由下的动态路由数据都会同步更新。
咱们的指望实际上是在使用keep-alive的状况下,动态路由能有非动态的表现,即拥有完整的生命周期、各自的数据缓存。
入手keep-alive源码发现,其实问题就出如今这一步:
if (
// not included
(include && (!name || !matches(include, name))) ||
// excluded
(exclude && name && matches(exclude, name))
) {
return vnode
}
复制代码
经过上面的表象其实能够探究出,router-view实际上是已经缓存了,并且一个动态路由的router-view都是经过了if判断返回了Vnode。那么再看一下这个name是什么:
function getComponentName (opts: ?VNodeComponentOptions): ?string {
return opts && (opts.Ctor.options.name || opts.tag)
}
const name: ?string = getComponentName(componentOptions)
复制代码
这里的opts其实对应的就是VueComponent的$options,而this.$options.name不就是对应着得.vue文件里声明的name属性。而后又想到,怪不得配置路由的时候要求提供的name属性要和组件内部的name值保持一致。
看到这里,问题已经水落石出了,由于动态路由配置的组件相同,getComponentName每次返回相同name,而后render()去缓存了相同的Vnode,且只能缓存了一份。既然如此,只要能正确的缓存Vnode和取出Vnode,动态路由状况下,keep-alive依然能正常运行。
上面说到了是由于动态路由组件名的问题,若是将缓存的key设置为惟一不就好了吗?
因而在router-view上配置key,key取得师path,永远惟一:
<keep-alive :include="cacheList">
<router-view :key="$route.path"></router-view>
</keep-alive>
复制代码
而后修改keep-alive.js源码,以下(由于放假的关系不详细说了,直接贴源码,实现的人就是我,也是第一个,github上此BUG目前仍是open状态):
/*
*@flow
*modify by LK 20190624
*/
import { isRegExp, remove } from 'shared/util'
import { getFirstComponentChild } from 'core/vdom/helpers/index'
type VNodeCache = { [key: string]: ?VNode };
function getComponentName (opts: ?VNodeComponentOptions): ?string {
return opts && (opts.Ctor.options.name || opts.tag)
}
function matches (pattern: string | RegExp | Array<string>, key: string | Number): boolean {
if (Array.isArray(pattern)) {
return pattern.indexOf(key) > -1
} else if (typeof pattern === 'string') {
return pattern.split(',').indexOf(key) > -1
} else if (isRegExp(pattern)) {
return pattern.test(key)
}
/* istanbul ignore next */
return false
}
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 (key && !filter(key)) {
pruneCacheEntry(cache, key, keys, _vnode)
}
}
}
}
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)
}
const patternTypes: Array<Function> = [String, RegExp, Array]
export default {
name: 'keep-alive',
abstract: true,
props: {
include: patternTypes,
exclude: patternTypes,
max: [String, Number]
},
created () {
this.cache = Object.create(null)
this.keys = []
},
destroyed () {
for (const key in this.cache) {
pruneCacheEntry(this.cache, key, this.keys)
}
},
mounted () {
this.$watch('include', val => {
pruneCache(this, key => matches(val, key))
})
this.$watch('exclude', val => {
pruneCache(this, key => !matches(val, key))
})
},
render () {
const slot = this.$slots.default
const vnode: VNode = getFirstComponentChild(slot)
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
const componentOptions: ?VNodeComponentOptions = vnode && vnode.componentOptions
if (componentOptions) {
// check pattern
const name: ?string = getComponentName(componentOptions)
const { include, exclude } = this
if (
// not included
(include && (!key || !matches(include, key))) ||
// excluded
(exclude && key && matches(exclude, key))
) {
return vnode
}
const { cache, keys } = this
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])
}
}
复制代码
由于放假赶车的关系,粗略说一下,有问题直接在底下评论:
npm install 时不下载vue,修改packjson.js改成本地的vue:"vue": "file:./vue2.5.0/"
"dependencies": {
"axios": "^0.18.0",
"clipboard": "^2.0.0",
"codemirror": "^5.38.0",
"countup": "^1.8.2",
"cropperjs": "^1.2.2",
"dayjs": "^1.7.7",
"echarts": "^4.0.4",
"html2canvas": "^1.0.0-alpha.12",
"iview": "^3.2.2",
"iview-area": "^1.5.17",
"js-cookie": "^2.2.0",
"simplemde": "^1.11.2",
"sortablejs": "^1.7.0",
"tree-table-vue": "^1.1.0",
"v-org-tree": "^1.0.6",
"vue": "file:./vue2.5.0/",
"vue-i18n": "^7.8.0",
"vue-router": "^3.0.1",
"vuedraggable": "^2.16.0",
"vuex": "^3.0.1",
"wangeditor": "^3.1.1",
"xlsx": "^0.13.3"
},
复制代码
// import Vue from 'vue'
import Vue from '../vue-2.5.10/src/core/index'
复制代码