zoukankan      html  css  js  c++  java
  • 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>
  • 相关阅读:
    【BZOJ1006】神奇的国度(弦图)
    弦图
    【BZOJ2946】公共串(后缀数组)
    【POJ1743】Musical Theme(后缀数组)
    JAVA和Tomcat运维整理
    linux shell 之if-------用if做判断
    Linux curl命令详解
    Intel HEX文件解析
    Linux bridge-utils tunctl 使用
    怎样查询锁表的SQL
  • 原文地址:https://www.cnblogs.com/zhanglanzuopin/p/15273211.html
Copyright © 2011-2022 走看看