欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Vue項(xiàng)目中keepAlive的使用說(shuō)明(超級(jí)實(shí)用版)

 更新時(shí)間:2022年04月15日 15:28:35   作者:魯智深拳打陳冠希  
這篇文章主要介紹了Vue項(xiàng)目中keepAlive的使用說(shuō)明,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教

keepAlive的使用

在開(kāi)發(fā)的過(guò)程中如果碰到經(jīng)常瀏覽需要緩存的頁(yè)面,而且頁(yè)面很長(zhǎng)需要記錄滾動(dòng)的位置這時(shí)就需要用到keepAlive。

一共有三個(gè)步驟

1、首先在路由中的mate屬性中記錄keepAlive,如果需要緩存則置為true。

path:'/index',
name:''index',
component:()=>import('../../index/index'),
meta:{keepAlive:true}

2、在創(chuàng)建router實(shí)例的時(shí)候加上scrollBehavior方法(keepAlive才會(huì)生效)。

let router=new Router({
? ? mode:"hash",//1、hash哈希:有#號(hào)。2、history歷史:沒(méi)有#號(hào)
? ? base:process.env.BASE_URL, //自動(dòng)獲取根目錄路徑
? ? scrollBehavior:(to,from,position)=>{
? ? ? ? if(position){
? ? ? ? ? ? return position
? ? ? ? }else{
? ? ? ? ? ? return {x:0,y:0}
? ? ? ? }
? ? },

3、需要緩存的router-view包上keep-alive(要有兩個(gè)router-view,一個(gè)是緩存的時(shí)候顯示,一個(gè)是不緩存的時(shí)候顯示,有的時(shí)候不需要緩存)。

<keep-alive>
?? ?<router-view v-if="$router.meta.keepAlive"></router-view>
</keep-alive>
?? ?<router-view v-if="!$router.meta.keepAlive"></router-view>

注意

在keep-alive中的組件會(huì)有兩個(gè)生命周期的鉤子函數(shù),activated和deactivated,其中activated是在組件第一次渲染時(shí)會(huì)被調(diào)用,而且之后每次緩存組件被激活都會(huì)被調(diào)用。所以一般使用時(shí)需要里面的代碼和created函數(shù)中的代碼一樣即可。

keepAlive的注意事項(xiàng)

問(wèn)題描述

今天在測(cè)試提到了一個(gè)bug,當(dāng)重復(fù)進(jìn)入相同的組建的時(shí)候,mounted和created內(nèi)的方法不觸發(fā),導(dǎo)致頁(yè)面展示不一樣

原因

<keep-alive> 包裹動(dòng)態(tài)組件時(shí),會(huì)緩存不活動(dòng)的組件實(shí)例,而不是銷毀它們。和 <transition> 相似,<keep-alive> 是一個(gè)抽象組件:它自身不會(huì)渲染一個(gè) DOM 元素,也不會(huì)出現(xiàn)在父組件鏈中。(所以不會(huì)觸發(fā)mounted和created事件鉤子)

當(dāng)組件在 <keep-alive> 內(nèi)被切換,它的 activated (激活)和 deactivated (不激活)這兩個(gè)生命周期鉤子函數(shù)將會(huì)被對(duì)應(yīng)執(zhí)行。

include and exclude

include (緩存的文件)和 exclude(不換存文件) 屬性允許組件有條件地緩存。

<!-- 逗號(hào)分隔字符串 -->
<keep-alive include="a,b">
? <component :is="view"></component>
</keep-alive>
?
<!-- 正則表達(dá)式 (使用 `v-bind`) -->
<keep-alive :include="/a|b/">
? <component :is="view"></component>
</keep-alive>
?
<!-- 數(shù)組 (使用 `v-bind`) -->
<keep-alive :include="['a', 'b']">
? <component :is="view"></component>
</keep-alive>

max

最多可以緩存多少組件實(shí)例。

<keep-alive :max="10">
? <component :is="view"></component>
</keep-alive>

以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論