溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

怎么提高修改vue源碼實現(xiàn)動態(tài)路由緩存

發(fā)布時間:2021-03-16 15:42:24 來源:億速云 閱讀:264 作者:Leah 欄目:web開發(fā)

怎么提高修改vue源碼實現(xiàn)動態(tài)路由緩存?針對這個問題,這篇文章詳細介紹了相對應(yīng)的分析和解答,希望可以幫助更多想解決這個問題的小伙伴找到更簡單易行的方法。

可以通過 this.$route.params.taskId 來獲取當(dāng)前路由的 taskId 。

{
  path: 'CheckInputInfo/:taskId',
  meta: {
   title: '盤點錄入單'
  },
  name: 'CheckInputInfo',
  component: () => import('@/view/Check/CheckInputInfo.vue')
 }

類似的,同樣也可使用 query 方式,這時只需要在 path 后面配置 :taskId 即可實現(xiàn) CheckInputInfo?taskId=1 CheckInputInfo?taskId=2 這樣的路由,同時可以通過 this.$route.query.taskId 來獲取當(dāng)前路由的 taskId 。

{
  path: 'CheckInputInfo:taskId',
  meta: {
   title: '盤點錄入單'
  },
  name: 'CheckInputInfo',
  component: () => import('@/view/Check/CheckInputInfo.vue')
 }

vue-router 通過配置 params query 來實現(xiàn)動態(tài)路由,并可通過 this.$route.xx 來獲取當(dāng)前的 params query ,省去了直接操作或處理 window.location ,還是挺方便的。

注意 :當(dāng)使用路由參數(shù)時,例如從 /user/foo 導(dǎo)航到 /user/bar,原來的組件實例會被復(fù)用。因為兩個路由都渲染同個組件,比起銷毀再創(chuàng)建,復(fù)用則顯得更加高效。不過,這也意味著組件的生命周期鉤子不會再被調(diào)用。

解讀:在不使用 keep-alive 的情況下,我們每次加載路由,這時會重新 render 當(dāng)前路由掛載的 component ,但若這兩個路由是同一個路由組件配置的動態(tài)路由, vue 為了性能設(shè)計了不會重新 render 。

這顯然不符合我們的預(yù)期,那么該如何在動態(tài)路由下?lián)碛型暾纳芷谀??答案?keep-alive

keep-alive

官網(wǎng)解讀 :keep-alive 包裹動態(tài)組件時,會緩存不活動的組件實例,而不是銷毀它們。和 transition 相似,keep-alive 是一個抽象組件:它自身不會渲染一個 DOM 元素,也不會出現(xiàn)在組件的父組件鏈中。在 2.2.0 及其更高版本中,activated 和 deactivated 將會在 樹內(nèi)的所有嵌套組件中觸發(fā)。當(dāng)組件在 內(nèi)被切換,它的 activated 和 deactivated 這兩個生命周期鉤子函數(shù)將會被對應(yīng)執(zhí)行。

keep-alive通過緩存Vnode的方式解決了SPA最為關(guān)鍵的性能問題。以下,我就按步驟來分析以下:

一、路由觸發(fā)路由組件重新render的問題

1、不緩存模式:

<router-view></router-view>

怎么提高修改vue源碼實現(xiàn)動態(tài)路由緩存

每次切換都會重新 render ,執(zhí)行整個生命周期,每次切換時,重新 render ,重新請求,,必然不滿足需求。

2、緩存模式:

<keep-alive>
 <router-view></router-view>
</keep-alive>

怎么提高修改vue源碼實現(xiàn)動態(tài)路由緩存

只是在進入當(dāng)前路由的第一次 render ,來回切換不會重新執(zhí)行生命周期,且能緩存 router-view 的數(shù)據(jù)。

二、router-view 數(shù)據(jù)緩存問題

keep-alive 采用 render 函數(shù)來創(chuàng)建 Vnode ,一下是 vue v2.5.10 keep-alive.js render()

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

于是當(dāng)時用 keep-alive 時,我們就可以保存每個 route-view 的數(shù)據(jù)。

動態(tài)路由緩存問題及如何實現(xiàn)

一、bug表象

最開始其實是不知道這個 bug 的,也是通過現(xiàn)象反推,然后由源碼解決這個問題的,那就先從現(xiàn)象說起:

動態(tài)路由緩存的的具體表現(xiàn)在:

由動態(tài)路由配置的路由只能緩存一份數(shù)據(jù)。 keep-alive 動態(tài)路由只有第一個會有完整的生命周期,之后的路由只會觸發(fā) actived deactivated 這兩個鉤子。 一旦更改動態(tài)路由的某個路由數(shù)據(jù),期所有同路由下的動態(tài)路由數(shù)據(jù)都會同步更新。

我們的期望其實是在使用 keep-alive 的情況下,動態(tài)路由能有非動態(tài)的表現(xiàn),即擁有 完整的生命周期各自的數(shù)據(jù)緩存 。

二、發(fā)掘問題關(guān)鍵

入手 keep-alive 源碼發(fā)現(xiàn),其實問題就出現(xiàn)在這一步:

if (
 // not included
 (include && (!name || !matches(include, name))) ||
 // excluded
 (exclude && name && matches(exclude, name))
) {
 return vnode
}

通過上面的表象其實可以探究出, router-view 其實是已經(jīng)緩存了,而且一個動態(tài)路由的 router-view 都是通過了 if 判斷返回了 Vnode 。那么再看一下這個 name 是什么:

function getComponentName (opts: ?VNodeComponentOptions): ?string {
 return opts && (opts.Ctor.options.name || opts.tag)
}
const name: ?string = getComponentName(componentOptions)

這里的 opts 其實對應(yīng)的就是 VueComponent $options ,而 this.$options.name 不就是對應(yīng)著得 .vue 文件里聲明的 name 屬性。然后又想到,怪不得配置路由的時候要求提供的 name 屬性要和組件內(nèi)部的 name 值保持一致。

看到這里,問題已經(jīng)水落石出了,因為動態(tài)路由配置的組件相同, getComponentName 每次返回相同 name ,然后 render() 去緩存了相同的 Vnode ,且只能緩存了一份。既然如此,只要能正確的緩存 Vnode 和取出 Vnode ,動態(tài)路由情況下, keep-alive 依然能正常運行。

修改Vue源碼

上面說到了是因為動態(tài)路由組件名的問題,如果將緩存的 key 設(shè)置為唯一不就行了嗎?

于是在 router-view 上配置key,key取得師path,永遠唯一:

<keep-alive :include="cacheList">
 <router-view :key="$route.path"></router-view>
</keep-alive>

然后修改 keep-alive.js 源碼,如下(因為放假的關(guān)系不詳細說了,直接貼源碼,實現(xiàn)的人就是我,也是第一個,github上此BUG目前還是open狀態(tài)):

/* 
*@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])
 }
}

如何集成

因為放假趕車的關(guān)系,粗略說一下,有問題直接在底下評論:

一、修改package.json:

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 為本地文件:

// import Vue from 'vue'
import Vue from '../vue-2.5.10/src/core/index'

關(guān)于怎么提高修改vue源碼實現(xiàn)動態(tài)路由緩存問題的解答就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關(guān)注億速云行業(yè)資訊頻道了解更多相關(guān)知識。

向AI問一下細節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

vue
AI