vue中keep-alive,include的指定頁面緩存問題


做vue項目時,有時要在某些頁面做緩存,而其它頁面不要。比如:A:首頁,B:獲取所有訂單頁面,C:訂單詳情頁面;從A(首頁)進入 B(獲取所有訂單)時應該不緩存,B(所有訂單)進入 C(訂單詳情)訂單后時再返回B,此時B(所有訂單頁面)緩存。不需要再次刷新,即:A->B->C時都是刷新,而C->B->A時B緩存。在vue官方文檔2.x以上有include 和 exclude 屬性允許組件有條件地緩存。在這里主要用include結合vuex來實現,include 是根據組件的name值來判斷的,所以三個頁面組件都有自己的name才會生效(重要是B必須有name),這里name就叫A,B,C。

首先安裝vuex

 npm install --save vuex

安裝后新建store.js

import Vue from "vue";
import Vuex from "vuex";

Vue.use(Vuex);

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

在main.js里面引入store.js;

import store from './store'
new Vue({
  el: '#app',
  // 注入 store
  store,
  router,
  components: { App },
  template: '<App/>',
})

在APP.vue頁面加入keepalive動態判斷

<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>

 

在A(首頁)進入 B時

<script>
    export default {
        name: 'A',
        methods: {
            goB() {
                this.$store.commit('setKeepAlive', ['B']) //設置緩存
          this.$router.push('/B') 
       } 
     } 
  }
</script>

在B頁面設置是否緩存

<script>
    export default {
        name: 'B',//組件名稱
        beforeRouteLeave (to, from, next) {
            if (to.path.indexOf('C') > -1) {
               this.$store.commit('setKeepAlive', ['B'])
            } else {
         this.$store.commit('setKeepAlive', []) 
            }
            next()
        }
 }
</script>   

這樣就可以了。 


免責聲明!

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



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