keep-alive A,B,C三个页面数据缓存问题

38 阅读1分钟

关于keep-alive组件缓存数据

B页面是表单页,缓存数据也就是保存用户填写的数据。

由A->B,B->A页面数据不需要缓存,由B->C,C->B页面需要缓存

业务场景:B页面为用户填写表单提交页,C页面为用户隐私协议等,用户查看隐私协议返回上一步保存填写的数据

在app.vue中添加

<keep-alive :include="keepAlive">
  <router-view/>
</keep-alive>

获取vuex中存储需要缓存的组件名称

 computed: {
    keepAlive() {
      this.$store.getters.keepAlive.push('register')
      return this.$store.getters.keepAlive
    }
  },

在vuex中keepAlive为存放所缓存组件的数组 通过setKeepAlive 赋值

const state  =  {
  keepAlive: []
}

const actions = {
  setKeepAlive: (state, keepAlive) => {
    state.state.keepAlive = keepAlive
  }
}

在B页面中 引入上述方法

...mapActions(["setKeepAlive"]),
beforeRouteLeave(to,from,next){
    if (to.name == 'rule') {
    // B页面跳转C页面数据需要缓存,所以调用方法将所需缓存的组件名称添加到keepAlives数组中
      this.setKeepAlive(['applyForm'])
      next()
    } else {
    // B页面跳转其他页面 数据不需要缓存
      this.setKeepAlive([])
      next()
    }
  }

值得注意的是使用此方法是组件name属性必须要存在

image.png 也尝试过通过keep-alive组件的生命周期activated实现 无果

往大佬们不吝赐教

以上是个人使用心得 如有不足之处 烦请指出