keep-alive 實現從列表頁到詳情頁,而後再回到列表頁並保持原來列表頁的頁碼數,而且只刷新數據

思路:緩存

keep-alive應用場景介紹 函數

  • <keep-alive> 不會在函數式組件中正常工做,由於它們沒有緩存實例。
    結合router,緩存部分頁面
  • activated 和 deactivate 生命週期鉤子
  • include string或正則,只有名稱匹配的組件會被緩存 2.1.0+佈局

  • exclude string或正則, 名稱匹配的組件不會被緩存 2.1.0+this

  • max 最多能夠緩存多少組件實例 2.5.0+

例子:spa

<keep-alive include="a,b" :include="['a','b']" :exclude="/a|b/" :max="10">
  <component :is='view'></component>
</keep-alive>

 

下面開始講解應用在保留列表當前頁的案例中:code

結合router,緩存部分頁面component

1. 佈局router-view中router

<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的元信息 metablog

 1 {
 2     path: '/dm',
 3     component: Layout,
 4     redirect: '/dm/basic',
 5     name: '設備中心',
 6     meta: {
 7       title: '設備中心',
 8       icon: '&#xe605;'
 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時每次都會走的鉤子函數

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()
  },

 

效果以下:

相關文章
相關標籤/搜索