美文网首页
vue中keep-alive,include的指定页面缓存问题

vue中keep-alive,include的指定页面缓存问题

作者: 问题_解决_分享_讨论_最优 | 来源:发表于2019-12-12 09:26 被阅读0次

    做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

        }

    });<br><br>

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

    import storefrom'./store'new Vue({

      el: '#app',

      // 注入 store  store,

      router,

      components: { App },

      template: '<App/>',

    })

    在APP.vue页面加入keepalive动态判断

                      export default {

      data () {

        return {}

      },

      computed: {

        keepAlive () {

          returnthis.$store.getters.keepAlive

        }

      }

    }

    在A(首页)进入 B时

        export default {

            name: 'A',

            methods: {

                goB() {

                    this.$store.commit('setKeepAlive', ['B']) //设置缓存

              this.$router.push('/B')

           }

         }

      }

    在B页面设置是否缓存

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

            }

     }

    这样就可以了。

    打个广告,本人博客地址是:风吟个人博客

    相关文章

      网友评论

          本文标题:vue中keep-alive,include的指定页面缓存问题

          本文链接:https://www.haomeiwen.com/subject/wnyzgctx.html