keep-alive是Vue.js的一個內建元件。這篇文章主要介紹了vue.js內建元件之keep-alive元件使用,需要的朋友可以參考下
keep-alive是Vue.js的一個內建元件。
舉個栗子
<keep-alive> <router-view v-if="$route.meta.keepAlive"></router-view> </keep-alive> <router-view v-if="!$route.meta.keepAlive"></router-view>
#在點擊button時候,兩個input會發生切換,但是這時候這兩個輸入框的狀態會被快取起來,input標籤中的內容不會因為元件的切換而消失。
* include - 字串或正規表示式。只有匹配的組件會被快取。
* exclude - 字串或正規表示式。任何符合的元件都不會被快取。
<keep-alive include="a"> <component></component> </keep-alive>
只快取元件別民name為a的元件
<keep-alive exclude="a"> <component></component> </keep-alive>
除了name為a的元件,其他都緩存下來
#生命週期鉤子
生命鉤子keep-alive提供了兩個生命鉤子,分別是activated與deactivated。
因為keep-alive會將組件保存在內存中,並不會銷毀以及重新創建,所以不會重新調用組件的created等方法,需要用activated與deactivated這兩個生命鉤子來得知當前組件是否處於活動狀態。
深入keep-alive元件實作
#檢視vue--keep-alive元件原始碼可以得到以下資訊
# created鉤子會建立一個cache對象,用來作為快取容器,並保存vnode節點。
props: { include: patternTypes, exclude: patternTypes, max: [String, Number] }, created () { // 创建缓存对象 this.cache = Object.create(null) // 创建一个key别名数组(组件name) this.keys = [] },
destroyed鉤子則在元件被銷毀的時候清除cache快取中的所有元件實例。
destroyed () { /* 遍历销毁所有缓存的组件实例*/ for (const key in this.cache) { pruneCacheEntry(this.cache, key, this.keys) } },
:::demo
render () { /* 获取插槽 */ const slot = this.$slots.default /* 根据插槽获取第一个组件组件 */ const vnode: VNode = getFirstComponentChild(slot) const componentOptions: ?VNodeComponentOptions = vnode && vnode.componentOptions if (componentOptions) { // 获取组件的名称(是否设置了组件名称name,没有则返回组件标签名称) const name: ?string = getComponentName(componentOptions) // 解构对象赋值常量 const { include, exclude } = this if ( /* name不在inlcude中或者在exlude中则直接返回vnode */ // 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) // 判断是否设置了最大缓存实例数量,超过则删除最老的数据, if (this.max && keys.length > parseInt(this.max)) { pruneCacheEntry(cache, keys[0], keys, this._vnode) } } // 给vnode打上缓存标记 vnode.data.keepAlive = true } return vnode || (slot && slot[0]) } // 销毁实例 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) } // 缓存 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) // 组件name 不符合filler条件, 销毁实例,移除cahe if (name && !filter(name)) { pruneCacheEntry(cache, key, keys, _vnode) } } } } // 筛选过滤函数 function matches (pattern: string | RegExp | Array<string>, name: string): boolean { if (Array.isArray(pattern)) { return pattern.indexOf(name) > -1 } else if (typeof pattern === 'string') { return pattern.split(',').indexOf(name) > -1 } else if (isRegExp(pattern)) { return pattern.test(name) } /* istanbul ignore next */ return false } // 检测 include 和 exclude 数据的变化,实时写入读取缓存或者删除 mounted () { this.$watch('include', val => { pruneCache(this, name => matches(val, name)) }) this.$watch('exclude', val => { pruneCache(this, name => !matches(val, name)) }) },##:::透過檢視Vue原始碼可以看出,keep-alive預設傳遞3個屬性,include 、exclude、max, max 最大可快取的長度結合原始碼我們可以實作一個可設定快取的router -view
<!--exclude - 字符串或正则表达式。任何匹配的组件都不会被缓存。--> <!--TODO 匹配首先检查组件自身的 name 选项,如果 name 选项不可用,则匹配它的局部注册名称--> <keep-alive :exclude="keepAliveConf.value"> <router-view class="child-view" :key="$route.fullPath"></router-view> </keep-alive> <!-- 或者 --> <keep-alive :include="keepAliveConf.value"> <router-view class="child-view" :key="$route.fullPath"></router-view> </keep-alive> <!-- 具体使用 include 还是exclude 根据项目是否需要缓存的页面数量多少来决定-->建立一個keepAliveConf.js 放置需要匹配的元件名稱##
// 路由组件命名集合 var arr = ['component1', 'component2']; export default {value: routeList.join()};
#配置重置快取的全域方法
import keepAliveConf from 'keepAliveConf.js' Vue.mixin({ methods: { // 传入需要重置的组件名字 resetKeepAive(name) { const conf = keepAliveConf.value; let arr = keepAliveConf.value.split(','); if (name && typeof name === 'string') { let i = arr.indexOf(name); if (i > -1) { arr.splice(i, 1); keepAliveConf.value = arr.join(); setTimeout(() => { keepAliveConf.value = conf }, 500); } } }, } })
在適當的時機呼叫呼叫this.resetKeepAive(name),觸發keep-alive銷毀元件實例;
Vue.js內部將DOM節點抽象化了一個個的VNode節點,keep-alive元件的快取也是基於VNode節點的而不是直接儲存DOM結構。它將滿足條件的元件在cache物件中快取起來,在需要重新渲染的時候再將vnode節點從cache物件中取出並渲染。
以上是實例詳解vue.js內建組件之keep-alive組件的使用的詳細內容。更多資訊請關注PHP中文網其他相關文章!

vue中props可以传递函数;vue中可以将字符串、数组、数字和对象作为props传递,props主要用于组件的传值,目的为了接收外面传过来的数据,语法为“export default {methods: {myFunction() {// ...}}};”。

本篇文章带大家聊聊vue指令中的修饰符,对比一下vue中的指令修饰符和dom事件中的event对象,介绍一下常用的事件修饰符,希望对大家有所帮助!

如何覆盖组件库样式?下面本篇文章给大家介绍一下React和Vue项目中优雅地覆盖组件库样式的方法,希望对大家有所帮助!

react与vue的虚拟dom没有区别;react和vue的虚拟dom都是用js对象来模拟真实DOM,用虚拟DOM的diff来最小化更新真实DOM,可以减小不必要的性能损耗,按颗粒度分为不同的类型比较同层级dom节点,进行增、删、移的操作。


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

AI Hentai Generator
免費產生 AI 無盡。

熱門文章

熱工具

Safe Exam Browser
Safe Exam Browser是一個安全的瀏覽器環境,安全地進行線上考試。該軟體將任何電腦變成一個安全的工作站。它控制對任何實用工具的訪問,並防止學生使用未經授權的資源。

DVWA
Damn Vulnerable Web App (DVWA) 是一個PHP/MySQL的Web應用程序,非常容易受到攻擊。它的主要目標是成為安全專業人員在合法環境中測試自己的技能和工具的輔助工具,幫助Web開發人員更好地理解保護網路應用程式的過程,並幫助教師/學生在課堂環境中教授/學習Web應用程式安全性。 DVWA的目標是透過簡單直接的介面練習一些最常見的Web漏洞,難度各不相同。請注意,該軟體中

SublimeText3 英文版
推薦:為Win版本,支援程式碼提示!

EditPlus 中文破解版
體積小,語法高亮,不支援程式碼提示功能

SublimeText3 Linux新版
SublimeText3 Linux最新版