动态keep-alive缓存组件

分析

案例场景:
问题:
1、项目详情页需要进行keep-alive缓存
2、进入一个项目的详情页,在进入另外一个项目详情页,发现展示的还是上个项目的详情页(被缓存了)
实现:
keep-alive组件的exclude属性结合页面路由守卫和vuex实现
exclude  值:字符串或正则表达式      任何名称匹配的组件都不会被缓存。
keep-alive其他学习参考官网:https://cn.vuejs.org/guide/built-ins/keep-alive.html#include-exclude

实现

1、keep-alive缓存路由组件

<keep-alive :exclude="$store.getters.vulnRouteInfo">
      <router-view
        v-if="$route.meta.keepAlive && flag"
        class="layoutMain"
      ></router-view>
    </keep-alive>
    <router-view
      v-if="!$route.meta.keepAlive && flag"
      class="layoutMain"
    ></router-view>

2、vuex中封装vulnRouteInfo参数

const state: any = {
  vulnRouteInfo: [],
}

const mutations: any = {
  setVulnRouteInfo(state: any, vulnRouteInfo: any) {
    state.vulnRouteInfo = vulnRouteInfo
  },
}
const actions = {
  setRouteInfo(context: any, val: string) {
    context.commit('setVulnRouteInfo', val)
  },
}

export default {
  state,
  mutations,
  actions,
}

3、页面路由监听

// ts页面路由引入
import { Component } from 'vue-property-decorator'
Component.registerHooks([
  'beforeRouteEnter',
  'beforeRouteLeave',
  'beforeRouteUpdate',
])
export default class ProjectDetail extends VueBase {
	beforeRouteLeave(to: any, from: any, next: any) {
	    if (to.meta.i18n === 'menu.vulnDetail') {
	      this.$store.dispatch('setRouteInfo', [])
	    } else {
	    	// 取消缓存
	      this.$store.dispatch('setRouteInfo', ['ProjectIndex', 'ProjectDetail'])
	    }
	    console.log('@store', this.$store.getters.vulnRouteInfo)
	    next()
	  }
····其他代码
}

你可能感兴趣的:(积累,vue.js)