天天看點

vue keep-alive應用場景及如何使用

一、應用場景:

在開發中經常有從清單跳到詳情頁,然後傳回詳情頁的時候需要緩存清單頁的原來資料以及滾動位置,這個時候就需要儲存狀态,要緩存狀态。

概括來講:

1、清單頁面 ——進入詳情頁 —— 後退到清單頁(緩存清單頁的原來資料以及滾動位置)

2、重新進入清單頁面,擷取最新的資料

二、如何使用

在vue2.1.0版本之後的使用方法(推薦方法)

1、建立router執行個體的時候加上scrollBehavior方法

//在router中的index.js
const router = new VueRouter({
  mode: 'hash',
  base: process.env.BASE_URL,
  routes,
  scrollBehavior(to,from,savedPosition){
    if (savedPosition){
      return savedPosition
    }else{
      return{
        x:0,
        y:0
      }
    }
  }
})
           

2、在store裡加入需要緩存的的元件的變量名,和相應的方法

export default new Vuex.Store({
  state: {
    includeList:[]
  },
  mutations: {
    get_include(state,data){
      state.includeList = data;
    }
})
           

3、在App.vue中

<!-- include 需要緩存的元件 -->
<keep-alive :include="includeList">
      <router-view />
</keep-alive>


<script>
    import { mapState } from 'vuex';
    export default {
        name: 'App',
        data() {
            return {
           
            }
        },
        computed: {
            ...mapState(['includeList'])
        },
        created() {

        }
    }
</script>
           

 4、在beforeRouteLeave鈎子函數裡控制需要緩存的元件

注意beforeRouteLeave導航守衛是必須寫在目前單頁面中,不能寫在App.vue中

beforeRouteLeave(to, from, next) { 
        //跳轉到詳情頁時緩存目前清單頁,反之不緩存
        if (to.path === '/GoodDetail') { 
            this.$store.commit('get_include', ['Home'])
        } else {
            this.$store.commit('get_include', [])
        }
        next()
    },
           
vue keep-alive應用場景及如何使用

此方法将需要緩存的元件儲存到全局變量,可以在路由的鈎子函數裡靈活的控制哪些元件需要緩存,那些不需要緩存,不需要每次再重新初始化資料,但是需要在vuex中儲存資料;

在vue2.1.0版本之前使用方法

1、meta标簽中記錄keepAlive的屬性為true

vue keep-alive應用場景及如何使用

2、 建立router執行個體的時候加上scrollBehavior方法

//在router中的index.js
const router = new VueRouter({
  mode: 'hash',
  base: process.env.BASE_URL,
  routes,
  scrollBehavior(to,from,savedPosition){
    if (savedPosition){
      return savedPosition
    }else{
      return{
        x:0,
        y:0
      }
    }
  }
})
           

3、在App.vue中 

//App.vue中
<keep-alive>
   <router-view v-if='$route.meta.keepAlive'></router-view>
</keep-alive>
<router-view v-if='!$route.meta.keepAlive'></router-view>
           

 4、有些情況下需要緩存有些情況下不需要緩存,可以在緩存的元件裡的路由鈎子函數中做判斷

注意beforeRouteLeave導航守衛是必須寫在目前單頁面中,不能寫在App.vue中

beforeRouteLeave (to, from, next) {
    if (to.path === '/goodDetail') {
      from.meta.keepAlive = true
    } else {
      from.meta.keepAlive = false
     // this.$destroy()
    }
    next()
  },
           
vue keep-alive應用場景及如何使用

但是這種方法有bug,首先第一次打開頁面的時候并不緩存,即第一次從清單頁跳到詳情頁,再回來并沒有緩存,後面在進入詳情頁才會被緩存。

并且隻會緩存第一次進入的狀态,不會重新請求資料,如果當頁面A選中一個分類跳到B頁面,再從B清單頁面跳往詳情頁,此時會緩存這個狀态,并且以後再從A頁面的其他分類跳到B頁面都不會重新被緩存,以至于每次從詳情頁傳回B頁面都會跳第一次緩存的狀态;當你的項目隻有一種狀态需要緩存,可以考慮使用這種方法 

參考資料:https://www.cnblogs.com/mary-123/p/11248178.html