xloud项目对于active-keep
作者:互联网
https://cn.vuejs.org/v2/api/#keep-alive
在数字管网这个项目中,他将所有tagsview的操作都放在tags-view这个组件中,他用tags-view来记录点击过的页面
initTags() { const affixTags = this.affixTags = this.filterAffixTags(this.routes) for (const tag of affixTags) { // Must have tag name if (tag.name) { this.$store.dispatch('tagsView/addVisitedView', tag) } } },
addTags() { const { name } = this.$route if (name) { this.$store.dispatch('tagsView/addView', this.$route) } return false },
store.js中
const state = { visitedViews: [], cachedViews: [] } mutations={ ADD_VISITED_VIEW: (state, view) => { if (state.visitedViews.some(v => v.path === view.path)) return state.visitedViews.push( Object.assign({}, view, { title: view.meta.title || 'no-name' }) ) }, ADD_CACHED_VIEW: (state, view) => { if (state.cachedViews.includes(view.path)) return if (!view.meta.noCache) { state.cachedViews.push(view.path)//组件没有name默认缓存的就是path } } } actions={ addView({ dispatch }, view) { dispatch('addVisitedView', view) dispatch('addCachedView', view) }, addVisitedView({ commit }, view) { commit('ADD_VISITED_VIEW', view) } }
appmain.vue ,这个项目本来使用的是<keep-alive :include="cachedViews">来判断是否对该组件缓存,但是因为这个incldueing默认匹配的是name属性所以理论上是没缓存,而且就算缓存了,即使在sotre中删除了tagsvie他也是没法清除缓存,vue缓存的组件他依然缓存着。所以我只需要全组件缓存,然后做删除缓存的功能就可以了。
<template> <section class="app-main"> <transition name="fade-transform" mode="out-in"> <!-- <keep-alive :include="cachedViews">--> <keep-alive> <router-view :key="key" /> </keep-alive> </transition> </section> </template> <script> export default { name: 'AppMain', computed: { cachedViews() { return this.$store.state.tagsView.cachedViews }, key() { return this.$route.path } } } </script>
main.js在总的js中,在beforeRouterLeave这个生命周期中把我们的删除缓存行为混入进去。找到缓存的地方然后删除就可以了。然后在keep-alive进行所有组件缓存。由于我才疏学浅,我只能在keep-alive的子组件中才能找到cache缓存的地方。
Vue.mixin({ beforeRouteLeave:function (to, from, next){ if(this._uid!=6){ /* var key = this.$vnode.key == null ? this.$vnode.componentOptions.Ctor.cid + (this.$vnode.componentOptions.tag ? `::${this.$vnode.componentOptions.tag}` : '') : this.$vnode.key;*/ var cache = this.$vnode.parent.componentInstance.cache; var keys = this.$vnode.parent.componentInstance.keys; var delKeys=[] var cachedViews=this.$store.state.tagsView.cachedViews keys.forEach(key=>{ let flag=false cachedViews.forEach(view=>{ if(key.includes(view)){ flag=true } }) if(!flag){ delKeys.push(key) } }) delKeys.forEach(key=>{ var index = keys.indexOf(key); if (index > -1) { keys.splice(index, 1); } delete cache[key]; }) } next() } })
标签:缓存,name,keep,state,xloud,key,active,cachedViews,view 来源: https://www.cnblogs.com/xwj-web/p/16326826.html