您好,登錄后才能下訂單哦!
vue使用keep-alive實(shí)現(xiàn)組件切換時(shí)保存原組件數(shù)據(jù)?相信很多沒有經(jīng)驗(yàn)的人對(duì)此束手無策,為此本文總結(jié)了問題出現(xiàn)的原因和解決方法,通過這篇文章希望你能解決這個(gè)問題。
使用keep-alive的過程
普通方法:直接使用keep-alive
<keep-alive> <router-view /> </keep-alive>
效果:雖然能使上傳文件組件存活,在切換組件時(shí)仍可繼續(xù)上傳
問題:其余各個(gè)組件都不會(huì)銷毀和重新掛起,導(dǎo)致所有組件的內(nèi)容不會(huì)更新
更好一點(diǎn)的方法:配置路由加以判斷是否適用keep-alive
路由js:
//ManageFiles組件需要重新掛起刷新數(shù)據(jù),而ManageUploadFile為上傳文件組件,故想之存活 { path:'files', name:'ManageFiles', component: () => import('../pages/course/manage/resource/files/Files'), }, { path:'uploadfile', name:'ManageUploadFile', meta:{ keepAlive:true //是否存活標(biāo)志 }, component: () => import('../pages/course/manage/resource/files/UploadFile'), },
切換組件:
<template> <div class="manageResource"> <keep-alive> <router-view v-if="$route.meta.keepAlive" /> </keep-alive> <router-view v-if="!$route.meta.keepAlive" /> </div> </template>
效果圖:
(1)一開始為File組件,mounted()打印'我是File'
(2)第一次切換為UploadFile組件,mounted()打印'我是UploadFile'
(3)再次切換回File組件,mounted()再次重新打印'我是File'
(4)最后再次切換回UploadFile組件,因?yàn)樗恢贝婊?,所以不?huì)重新觸發(fā)mounted()再次重新打印'我是UploadFile'
補(bǔ)充知識(shí):vue 動(dòng)態(tài)組件(tabs切換)keep-alive:主要用于保留組件狀態(tài)或避免重新渲染
通過keep-alive 保留數(shù)據(jù)值 填寫數(shù)據(jù)時(shí)切換到其他頁面,后返回當(dāng)前頁數(shù)據(jù)保留 ,主要用于保留組件狀態(tài)或避免重新渲染
<!--動(dòng)態(tài)組件-component使用--> <div class="app"> <ul> <li @click="currView='home'">首頁</li> <li @click="currView='abount'">關(guān)于我們</li> </ul> <!--通過keep-alive 保留數(shù)據(jù)值 填寫數(shù)據(jù)時(shí)切換到其他頁面,后返回當(dāng)前頁數(shù)據(jù)保留--> <keep-alive> <component :is="currView"></component> </keep-alive> </div>
<script type="text/x-Template" id="homeTemp"> <h3>首頁數(shù)據(jù)</h3> </script> <script type="text/x-Template" id="abountTemp"> <h3>關(guān)于我們數(shù)據(jù)<input type="text"/></h3> </script>
<script type="text/javascript"> var vm=new Vue({ el:'.app', data:{ currView:"home" }, components:{ "home":{ template:"#homeTemp" }, "abount":{ template:"#abountTemp" } } }); </script>
看完上述內(nèi)容,你們掌握vue使用keep-alive實(shí)現(xiàn)組件切換時(shí)保存原組件數(shù)據(jù)的方法了嗎?如果還想學(xué)到更多技能或想了解更多相關(guān)內(nèi)容,歡迎關(guān)注億速云行業(yè)資訊頻道,感謝各位的閱讀!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。