利用vuex解决keep-alive缓存后点击左侧菜单进行初始化,点击tab也缓存数据问题

项目中遇到这样一个需求,需要tab切换,对数据进行缓存,这个时候,我们会想到vue自带的keep-alive进行缓存;但是此时,点击左侧菜单,界面依然是上一次缓存的数据,这就不满足需求了。下面讲解下如果利用vuex来解决这个问题。

1、在左侧菜单点击方法模块,增加如下代码

import { mapMutations } from 'vuex'
export default {
  methods: {
    ...mapMutations('d2admin/init', ['setRefreshPage']),
    handleMenuSelect (index, indexPath) {
      this.setRefreshPage(true)
      this.$router.push({
        path: index
      })
    }
  }
}

2、去相应的菜单点击模块编写代码(分为4步)

/** 新需求,点击菜单初始化*/
import { mapState, mapMutations } from 'vuex'
  /** 新需求,点击菜单初始化,*/
  activated () {
      console.log(this.refreshPage)
      if (this.refreshPage) {
          // 若为true,则执行重置页面等相关操作
          this.setRefreshPage(false)
          //这里写手动初始化的代码
      } else {
          console.log('点击菜单初始化')
      }
  },
  /** 新需求,点击菜单初始化,*/
  computed: {
      ...mapState('d2admin/init', [
          'refreshPage' // 映射 this.refreshSearch 为 this.$store.state.refreshSearch
      ])
  },
methods: {
    /** 新需求,点击菜单初始化,*/
    ...mapMutations('d2admin/init', ['setRefreshPage']),
}

完成到这里,你会发现需求基本满足,但是唯一不满足的,就是左侧菜单点击当前界面,界面不会初始化。

3、为了解决这个问题,这个时候,我们利用一个空界面来解决这个问题

创建一个vue文件

<!--此模块为空白页,点击左侧菜单为当前页,进行的过渡界面,再跳回原始页面-->
<template>
  <div></div>
</template>

<script>
    export default {
        name:'init',
        data(){
            return{
            }
        },
        beforeCreate() {
            let url = this.$route.query
            let str = ''
            for(let i in url){
                str += url[i]
            }
            console.log(str, 'index')
            this.$router.replace({
                path: str
            })
        }
    }
</script>

<style scoped>

</style>

然后去相应的路由模块引入这个界面的路由

最后完善我们第一步的步骤,在左侧菜单点击方法模块修改代码,(增加一个判断如果是当前界面就跳转空白页进行过渡)

利用vuex解决keep-alive缓存后点击左侧菜单进行初始化,点击tab也缓存数据问题

import { mapMutations } from 'vuex'
export default {
  methods: {
    ...mapMutations('d2admin/init', ['setRefreshPage']),
    handleMenuSelect (index, indexPath) {
      /** 新需求,点击菜单初始化*/
      if(this.$route.path === index){
        this.setRefreshPage(true)
        this.$router.replace({
          path:'/init',
          query:index
        })
      }else{
        this.setRefreshPage(true)
        this.$router.push({
          path: index
        })
      }
    }
  }
}