Nuxt使用Keep-alive缓存页面

 Nuxt 项目中,页面缓存的问题一直是比较头疼的一件事,几乎都是很粗暴的告诉你使用 keep-alive

layouts 添加 keep-alive

default.vue

<template>
  <div>
    <nuxt :keep-alive="isKeepActive" :keep-alive-props="{ include: includeArr }" :class="applets === 4 ? 'isCarApp' : ''" />
    <span id="cnzz_stat"></span>
  </div>
</template>
<script>
import { mapState } from "vuex";
import wxSdk from "~/utils/wxSdk.js";
export default {
  computed: {
    ...mapState(["applets", "token", "goLogin","isKeepActive"])
  },
  data(){
    return{
      includeArr:['memberDetail'],// 包括在内的组件,是否刷新
    }
  },
}
</script>

页面实例

<template>
  <div class="page">
    <nav-bar :title="title"></nav-bar>
    <scroll-view
      :style="{ height: windowH }"
      scroll-y="true"
      @scrolltolower="scrolltolower"
    >
     <!--code--->
    </scroll-view>
  </div>
</template>
<script>
//  #ifndef MP-WEIXIN
import { ImagePreview, Toast } from "vant";
// #endif
import scrollView from "~/components/scroll-view.vue";
import { mapState } from "vuex";

export default {
  name:'memberDetail',// keep-alive 定义页面name
  components: {
    // #ifndef MP-WEIXIN
    scrollView,
    // #endif
  },
  
  computed: {
    ...mapState(["pubCommentStatus", "token"]),
  },
  beforeRouteLeave(to, from, next) {
    // 根据路由变化结合vuex,判断是否缓存
    if (to.path == "/act/member" || to.path == "/detail/commentResult") {
      this.$store.commit("SET_KEEPACTIVE", false); // 去除缓存,设置后会刷新组件
    }
    next();
  },
  data() {
    var that = this;
    return {
      title: "活动详情",
  },
  head() {
    return {
      title: this.title,
    };
  },
};
</script>

vuex

export const state = () => ({
    isKeepActive:false,// 是否缓存会员活动详情
})

export const mutations = {
    SET_KEEPACTIVE(state,bool){
        state.isKeepActive=bool;
    }
}

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

// Vue.use(Vuex)

// const store = new Vuex.Store({
//   state: {
//     test: 'xxxxx',
//     counter: 0
//   },
//   mutations: {
//     SetText(state, v) {
//                     state.text = v
//                 }
//   },
//   actions: {
//     setText: function({commit}, v) {
//                         commit('SetText', v)
//                 }
//   }
// })

// export default store

注意:在通过isKeepActive来控制keep-alive,需要注意isKeepActive变量改变会导致组件memberDetail重新渲染,在进入组件前就要控制好isKeepActive变量,避免不必要刷新


版权声明:本文为hahahhahahahha123456原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。