vue keep-alive 实现多标签缓存功能

效果如下

多标签样式就不介绍了,主要介绍用keep-alive缓存

1、在vuex 文件下中新建keepAlive.js文件,进行存储路由的集中管理

const keepAlive = {
  state: {
    cachedViews:[] //存储缓存路由的数据
  },
  mutations: {
    ADD_KEEPALIVE: (state, type) => { //添加
      state.cachedViews.push(type) 
    },
    REMOVE_KEEPALIVE:(state, type) => { //删除
      state.cachedViews = state.cachedViews.filter(item => item !== type)
    },
  }
}

export default keepAlive

2、引入到vuex中

import Vue from 'vue'
import Vuex from 'vuex'
import keepAlive from './keepAlive'
Vue.use(Vuex)

export default new Vuex.Store({
  modules: {
    keepAlive
  }
})

3、通过计算属性实时监听 cachedViews的变化 进行缓存

<template>
   <!-- 主体内容部分 -->
  <div class="main">
  <keep-alive :include="cachedViews.join(',')">
    <router-view />
  </keep-alive>
  </div>
</template>
<script>
  export default {
    name: "RouteView",
    data(){
      return {
      }
    },
    computed: {
      cachedViews(){
        return this.$store.state.keepAlive.cachedViews
      }
    },
  }
</script>

4、在多标签也中监听路由改变,改变后如果不存在就新增

    watch: {
     $route: {
      handler(newRoute) {
        let linkList = this.$store.state.keepAlive.cachedViews
        if (linkList.indexOf(newRoute.fullPath.split('/')[2]) < 0) { //如果不存在
          if (newRoute.fullPath.split('/')[2] !== 'videoRuntime' && newRoute.fullPath.split('/')[2] !== 'videoHistory') //不需要缓存的数据
            this.$store.commit('ADD_KEEPALIVE', newRoute.fullPath.split('/')[2]) //添加缓存数据
          this.pageList.push(Object.assign({}, newRoute)) //导航数据
        }
      },
      immediate: true,
      deep: true
    },
    },

5、多标签页中的删除

 remove(key) { //的到当前的key 也就是 路由地址
        if (this.pageList.length === 1) { 
          this.$message.warning('这是最后一页,不能再关闭了啦')
          return
        }
        this.$store.commit('REMOVE_KEEPALIVE',key.split('/')[2])
        this.pageList = this.pageList.filter(item => item.fullPath !== key)
  },

注意:name 和 路由的文件明要一致

猜你喜欢

转载自blog.csdn.net/qq_45689385/article/details/124168102