vue中keep-alive內建元件快取的例項程式碼
阿新 • • 發佈:2020-04-18
需求:
home 元件中有一個 name 的 data 資料。這個資料修改之後,再切換到其他的元件。再切換到 home 元件,希望 home 中 name 這個值是之前修改過的值。希望元件有快取。
keep-alive 的使用方式:
將要快取的元件使用 keep-alive 包裹住即可。
keep-alive優點的介紹:
1. 切換元件時,當前元件不會觸發銷燬的生命週期鉤子。也就是說不會銷燬了。
2. 切換回來時,也不會重新建立。(既然都沒有被銷燬,哪裡來的重新建立呢)
3. 會多出兩個生命週期的鉤子函式
a. activated 快取啟用 第一次會觸發、元件能被看到
一般根 created 做一樣的事情:請求資料
一般根 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/"
假定快取佇列是 [home,list]
現在進入about的時候 about 也會被快取上,這時會將之前的第一個給排出去 [home,list,about] => [list,about] 先進先出原則。
概念就這些上程式碼
1.vue連結:https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js
2.建立元件。(三個元件)
//元件一 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",
body部分
<div id="app"> //active是樣式來做高亮用v-bind來繫結 //@click自定義事件將例項裡的資料改為home //點選的時候會觸發component內建標籤更換為home <button :class="{ active: curPage === 'home' }" @click="curPage = 'home'"> home </button> <button :class="{ active: curPage === 'list' }" @click="curPage = 'list'"> list </button> <button :class="{ active: curPage === 'about' }" @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內建元件快取內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!