...data
});
},
setCacheView(state,data){ // 与setToolData类似
if(state.cacheView.includes(data.componentName))
return;
state.cacheView.push(data.componentName);
},
clearToolItem(state,detail){
const index = state.toolBarData.findIndex(item => item.detail === detail);
const isActive = router.app.$route.path == state.toolBarData[index]["detail"];
const len = state.toolBarData.length - 1;
state.toolBarData.splice(index,1);
(index == len || isActive) && router.push({path:state.toolBarData[state.toolBarData.length - 1]["detail"]});
},
clearCacheView(state,viewName){
const index = state.cacheView.findIndex(item => item == viewName);
state.cacheView.splice(index,1);
}
},
actions: {
commitToolBar({commit},data) {
commit("setToolData",data);
commit("setCacheView",data);
},
clearToolBar({commit},data){
commit("clearToolItem",data.detail);
},
clearCache({commit},data){
commit("clearCacheView",data);
}
}
}
入口文件缓存路由
在 App.vue 入口文件,使用 keep-alive 对匹配的路由组件进行缓存,监听当前路由变化,添加缓存路由和标签。
<template>
<el-main style="position:relative;margin-top:45px;">
<!--渲染标签的地方-->
<ToolBar></ToolBar>
<div class="routeWrap">
<transition name="fade-transform">
<keep-alive :include="cachedViews">
<router-view></router-view>
</keep-alive>
</transition>
</div>
</el-main>
</template>
<script>
export default {
watch: {
$route() {
// 路由组件名称(自定义)
const componentName =this.$route.matched[0]["components"]["default"][ "name"];
const detail = this.$route.path;
// 当前路由匹配到name
const name = this.$route.meta[0]["name"];
this.$store.dispatch("commitToolBar", { name, detail, componentName });
}
}
}
</script>ToolBar代码
这里使用了 elementui 的 el-tag 标签, el-tag 标签带有动画、关闭按钮、主题color等属性, close 函数是清除该标签和清除缓存路由(已访问过)。 click 主要是当对该标签项点击操作,则切换到该路由页面。其中 active 是该标签匹配到当前路由时候处于激活状态(颜色高亮), el-tag 的动画比较生硬,所以关闭了。
<template>
<div class="toolbar">
<el-tag
class="toolItem"
type="info"










