nuxt2 动态控制页面缓存

393 阅读1分钟

logo (2).png

场景:表单页跳转选择城市界面,选择后返回表单页填写的数据需要保留。从表单页跳转到其他页面不缓存表单页。

store下创建一个vuex模块 public

// 公共缓存
const state = () => ({
  //缓存页面
  keepAliveList: [],
})

const mutations = {
  SET_KEEPALIVElIST: (state, keepAliveList) => {
    state.keepAliveList = keepAliveList
  },
}

const actions = {
  // 增加keepAlive页面
  AddKeepAlive({ commit, rootState, state }, cacheName) {
    if (!state.keepAliveList.includes(cacheName)) {
      commit('SET_KEEPALIVElIST', [...state.keepAliveList, ...[cacheName]])
    }
  },
  // 删除keepAlive页面
  RemoveKeepAlive({ commit, rootState, state }, cacheName) {
    if (state.keepAliveList.includes(cacheName)) {
      commit('SET_KEEPALIVElIST',state.keepAliveList.filter((x) => x != cacheName))
    }
  },
} 

export default {
  namespace: true,
  state,
  mutations,
  actions,
}

在layouts的default.vue下

<!-- 原来 -->
<nuxt />
<!-- 现在 -->
<nuxt keep-alive :keep-alive-props="cache" />

<script>
export default {
  computed: {
    cache() {
      return { include: this.$store.state.public.keepAliveList }
    }
}
</script>

在页面使用

form.vue页面

<script>
export default {
  //必须设置名称
  name: 'form',
  beforeRouteEnter(to, from, next) {
    next((vm) => {
      vm.$store.dispatch("public/AddKeepAlive", "form")
      vm.$store.dispatch("public/AddKeepAlive", "citys")
    })
  },
  beforeRouteLeave(to, from, next) {
    if (!['/citys'].includes(to.path)) {
      this.$store.dispatch("public/RemoveKeepAlive", "form")
      this.$store.dispatch("public/RemoveKeepAlive", "citys")
    }
    next()
  },
  activated() {
    // 获取从citys页面传递的数据
    if (this.$route.query.citys) {
      
    }
  },
}
</script>

citys.vue页面

<script>
export default {
  //必须设置名称
  name: 'citys',
  beforeRouteLeave(to, from, next) {
    if (to.name === 'form') {
      if (this.selectedCitys.length > 0)
        to.query.citys = ["城市名称"]
    }
    next()
  }
}
</script>