vue中keep-alive內置組件緩存的實例代碼
需求:home 組件中有一個 name 的 data 數據。這個數據修改之后,再切換到其他的組件。再切換到 home 組件,希望 home 中 name 這個值是之前修改過的值。希望組件有緩存。keep-alive 的使用方式:將要緩存的組件使用 keep-alive 包裹住即可。keep-alive優點的介紹:1. 切換組件時,當前組件不會觸發銷毀的生命周期鉤子。也就是說不會銷毀了。2. 切換回來時,也不會重新創建。(既然都沒有被銷毀,哪里來的重新創建呢)3. 會多出兩個生命周期的鉤子函數a. activated 緩存激活 第一次會觸發、組件能被看到一般根 created 做一樣的事情:請求數據b.deactivated 緩存失活 組件不能被看到一般根 beforeDestroy 做一樣的事情: 清除定時器、移除全局事件監聽4. 可以在 vue devtools 上看見組件的緩存情況** keep-alive 的更多屬性設置**1. include 包含a. include=“組件1,組件2” 注意 逗號前后不要有空格b. :include='[組件1, 組件2]'c. :include='/^hello/'2. exclude 排除a. exclude=“組件1,組件2” 注意 逗號前后不要有空格b. :exclude='[組件1, 組件2]'c. :exclude='/^hello/'3. max 規定最大能緩存組件的數量,默認是沒有限制的假定緩存隊列是 [home, list]現在進入about的時候 about 也會被緩存上,這時會將之前的第一個給排出去 [home, list, about] => [list, about] 先進先出原則。
概念就這些上代碼
1.vue鏈接:https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js2.創建組件。(三個組件)
//組件一 Vue.component('home', { data() { return { name: '張三', }; }, template: ` <div> <h1>home</h1> <p>{{ name }}</p> <button @click='name = ’李四’'>修改name為 李四</button> </div> `, //實例創建完成的時候打印 created() { console.log('home created'); }, //實例銷毀前的打印 beforeDestroy() { console.log('home beforeDestroy'); }, //激活緩存的時候打印組件能被看到 activated() { console.log('home activated'); }, //緩存失活時打印 組件不能被看到 deactivated() { console.log('home deactivated'); }, }); //組件二 Vue.component('list', { template: ` <div> <h1>list</h1> </div> `,//激活緩存的時候打印組件能被看到 created() { console.log('list created'); },//緩存失活時打印 組件不能被看到 beforeDestroy() { console.log('list beforeDestroy'); }, });//組件三Vue.component('about', { template: ` <div> <h1>about</h1> </div> `,//激活緩存的時候打印組件能被看到 created() { console.log('about created'); },//緩存失活時打印 組件不能被看到 beforeDestroy() { console.log('about beforeDestroy'); }, });
3.創建實例。
Vue.component('home', { data() { return { name: '張三', }; },
body部分
<div id='app'> //active是樣式來做高亮用v-bind來綁定 //@click自定義事件將實例里的數據改為home //點擊的時候會觸發component內置標簽更換為home <button : @click='curPage = ’home’'> home </button> <button : @click='curPage = ’list’'> list </button> <button : @click='curPage = ’about’' > about </button> <hr /> //用keep-alive內置組件包裹componet內置組件v-bind綁定max作用是最多緩存兩個 <keep-alive :max='2'> <component :is='curPage'></component> </keep-alive> //方法二 //排除法排除了about只有home與list可以緩存 //<keep-alive exclude='about'> // <component :is='curPage'></component> //</keep-alive> //方法三 //選擇緩存法只有home與list可以被緩存 //keep-alive include='home,list'> //<component :is='curPage'></component> //</keep-alive> </div>
三種方法的具體用法在文章的開始的時候有介紹
總結
到此這篇關于vue中keep-alive內置組件緩存的實例代碼的文章就介紹到這了,更多相關vue keep-alive內置組件緩存內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!
相關文章:
