vue中keep-alive,include的緩存問題


前提:有A,B,C,D四個頁面,A是按鈕頁(點擊按鈕進入B頁面),B是訂單列表頁,C是訂單詳情頁,D是費用詳情頁

需求:順序是A->B->C->D,每次都刷新頁面,D->C->B時走緩存,但是每次從A到B都要刷新B頁面,從B到C需要刷新C頁面,從C到D要刷新D頁面

在vue官方文檔2.1以上有include 和 exclude 屬性允許組件有條件地緩存。在這里主要用include結合vuex來實現(四個頁面組件都有自己的name才會生效,這里name就叫A,B,C,D)

從D->C,從C->B,從B->A 可以寫一個公共的頭部返回組件,統一使用 this.$router.go(-1)返回前一頁

App.vue


<template> <div class="app"> <keep-alive :include="keepAlive" > <router-view/> </keep-alive> </div> </template> <script type='text/javascript'> export default { data () { return {} }, computed: { keepAlive () { return this.$store.getters.keepAlive } } } </script>

store.js

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    keepAlive: []
  },
  mutations: {
    SET_KEEP_ALIVE: (state, keepAlive) => {
      state.keepAlive = keepAlive
    }
  },
  getters: {
    keepAlive: state => state.keepAlive
  }
})

每次進入B頁面時先初始化 keepAlive(設置要走緩存的頁面)

A.vue

<script>
    export default {
        name: 'A',
        methods: {
            buttonClick () {
                this.$store.commit('SET_KEEP_ALIVE', ['B', 'C', 'D']) 
          this.$router.push('/B')
       }
     }
  }
</script>

B.vue 該頁面用來設置緩存和清除緩存

<script>
    export default {
        name: 'B',
        beforeRouteEnter (to, from, next) {
            next(vm => {
               if (from.path.indexOf('C') > -1) {
                    vm.$store.commit('SET_KEEP_ALIVE', ['B'])
               }
            })
        },
        beforeRouteLeave (to, from, next) {
            if (to.path.indexOf('C') > -1) {
               this.$store.commit('SET_KEEP_ALIVE', ['B', 'C'])
            } else if (to.path.indexOf('A') > -1) {
         this.$store.commit('SET_KEEP_ALIVE', []) 
} next() }  }
</script>

到這里就實現了需求

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM