思路:
- <keep-alive> 不會在函數式組件中正常工作,因為它們沒有緩存實例。
結合router,緩存部分頁面 - activated 和 deactivate 生命周期鈎子
-
include string或正則,只有名稱匹配的組件會被緩存 2.1.0+
-
exclude string或正則, 名稱匹配的組件不會被緩存 2.1.0+
- max 最多可以緩存多少組件實例 2.5.0+
例子:
<keep-alive include="a,b" :include="['a','b']" :exclude="/a|b/" :max="10"> <component :is='view'></component> </keep-alive>
下面開始講解應用在保留列表當前頁的案例中:
結合router,緩存部分頁面
1. 布局router-view中
<template> <div class="mainContainer-wrap"> <transition :name="name" mode="out-in" name="fade"> <keep-alive> <router-view v-if="this.$route.meta.keepAlive"></router-view> </keep-alive> </transition> <transition :name="name" mode="out-in" name="fade"> <router-view v-if="!this.$route.meta.keepAlive"></router-view> </transition> </div> </template> <script> export default { name: 'mainContainer', data () { return { name: this.$route.name } }, mounted () { // console.log(this.$route.meta.keepAlive) } } </script>
2.在router/設置route的元信息 meta
1 { 2 path: '/dm', 3 component: Layout, 4 redirect: '/dm/basic', 5 name: '設備中心', 6 meta: { 7 title: '設備中心', 8 icon: '' 9 }, 10 children: [{ 11 path: 'basic', 12 name: 'Basic', 13 component: Basic, 14 meta: { 15 title: '設備管理', 16 keepAlive: true // 需要緩存 17 } 18 }, { 19 path: 'basic/decDetail', 20 name: 'DeviceDetail', 21 component: DeviceDetail, 22 meta: { 23 title: '設備詳情', 24 level: 2, 25 hidden: true, 26 keepAlive: false // 不需要緩存 27 } 28 }] 29 },
使用keep-alive會將數據保留在內存中,如果每次進入頁面的時候要獲取最新的數據,需要 在 activated 生命周期中 重新獲取數據,承擔原來created 鈎子中獲取數據的任務
設置了keep-alive的組件
第一次進入: beforeRouteEnter => created => ... => activated => ... => deactivated
后續進入:beforeRouteEnter => activated => deactivated,
只有第一次進入該組件時,才會走created鈎子,需要緩存的組件中activated時每次都會走的鈎子函數
設置了keep-alive的組件
第一次進入: beforeRouteEnter => created => ... => activated => ... => deactivated
后續進入:beforeRouteEnter => activated => deactivated,
只有第一次進入該組件時,才會走created鈎子,需要緩存的組件中activated時每次都會走的鈎子函數
3. 列表頁鈎子函數設置
created () { this.getList() }, activated() { //只刷新數據,不改變整體的緩存 this.getList() }, mounted () { this.getProductName() }, //修改列表頁的meta值,false時再次進入頁面會重新請求數據。 beforeRouteLeave(to, from, next) { from.meta.keepAlive = false next() },
4. 詳情頁路由的鈎子函數設置
// 從詳情頁返回主頁時把主頁的keepAlive值設置為true(要做個判斷,判斷是不是返回到主頁的) beforeRouteLeave (to, from, next) { if (to.name === 'Basic') { to.meta.keepAlive = true } else { to.meta.keepAlive = false } next() },
效果如下:

