實例詳解vue.js內建組件之keep-alive組件的使用
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)) }) },
<!--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 根据项目是否需要缓存的页面数量多少来决定-->
// 路由组件命名集合 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中文網其他相關文章!

熱AI工具

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

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

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

AI Hentai Generator
免費產生 AI 無盡。

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

熱門話題

可以通過以下步驟為 Vue 按鈕添加函數:將 HTML 模板中的按鈕綁定到一個方法。在 Vue 實例中定義該方法並編寫函數邏輯。

在 Vue.js 中引用 JS 文件的方法有三種:直接使用 <script> 標籤指定路徑;利用 mounted() 生命週期鉤子動態導入;通過 Vuex 狀態管理庫進行導入。

在 Vue.js 中使用 Bootstrap 分為五個步驟:安裝 Bootstrap。在 main.js 中導入 Bootstrap。直接在模板中使用 Bootstrap 組件。可選:自定義樣式。可選:使用插件。

Vue.js 中的 watch 選項允許開發者監聽特定數據的變化。當數據發生變化時,watch 會觸發一個回調函數,用於執行更新視圖或其他任務。其配置選項包括 immediate,用於指定是否立即執行回調,以及 deep,用於指定是否遞歸監聽對像或數組的更改。

Vue.js 返回上一頁有四種方法:$router.go(-1)$router.back()使用 <router-link to="/"> 組件window.history.back(),方法選擇取決於場景。

在 Vue 中實現跑馬燈/文字滾動效果,可以使用 CSS 動畫或第三方庫。本文介紹了使用 CSS 動畫的方法:創建滾動文本,用 <div> 包裹文本。定義 CSS 動畫,設置 overflow: hidden、width 和 animation。定義關鍵幀,設置動畫開始和結束時的 transform: translateX()。調整動畫屬性,如持續時間、滾動速度和方向。

可以通過以下方法查詢 Vue 版本:使用 Vue Devtools 在瀏覽器的控制台中查看“Vue”選項卡。使用 npm 運行“npm list -g vue”命令。在 package.json 文件的“dependencies”對像中查找 Vue 項。對於 Vue CLI 項目,運行“vue --version”命令。檢查 HTML 文件中引用 Vue 文件的 <script> 標籤中的版本信息。

Vue.js 遍歷數組和對像有三種常見方法:v-for 指令用於遍歷每個元素並渲染模板;v-bind 指令可與 v-for 一起使用,為每個元素動態設置屬性值;.map 方法可將數組元素轉換為新數組。
