参考vue-element-admin页面结构
keep-alive:缓存的前提是菜单路由的的name:属性要和页面的name:属性值保持一致。可以都采用首字母大写形式
keep-alive数据缓存功能只能缓存俩级菜单,当大于俩级菜单时,缓存会失效。
keep-alive的三个属性
include: patternTypes, // 缓存白名单
exclude: patternTypes, // 缓存黑名单
max: [String, Number] // 缓存的组件
第一种处理方法:第一级layout中的AppMain.vue中,做keep-alive全缓存处理。当有不想缓存的数据时,在使用exclude进行过滤。
// 目录:src/layout/components/AppMain.vue// 页面信息全缓存<template><section class="app-main"><transition name="fade-transform" mode="out-in">// 页面信息全缓存<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>
store中的获取菜单名称的方式
目录:src/store/modules/tagsView.js。mutations方法前提:<keep-alive :include="cachedViews"><router-view :key="key" /></keep-alive>// noCache:true,不缓存信息,false:缓存信息ADD_CACHED_VIEW: (state, view) => {if (state.cachedViews.includes(view.name)) returnif (!view.meta.noCache) {state.cachedViews.push(view.name)}},
第二种方式:推荐方式,可以方便自定义页面缓存,只需按照keep-alive的缓存规则即可
// 目录:src/layout/components/AppMain.vue<template><section class="app-main"><transition name="fade-transform" mode="out-in"><keep-alive :include="cachedViews"><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>
store中的获取菜单名称的方式
// 目录:src/store/modules/tagsView.js。mutations方法ADD_CACHED_VIEW: (state, view) => {if (state.cachedViews.includes(view.name)) return;const { matched, meta, name } = view;if (!meta.noCache) {if (matched.length > 2) {//路由层级大于2时,将父级也加入cachedViewsfor (let i = 1; i < matched.length; i++) {if (!state.cachedViews.includes(matched[i].name)) {state.cachedViews.push(matched[i].name);}}} else {state.cachedViews.push(name);}}},
大于等于三级以上页面的layout扩展页面
/* router模板 用于增加菜单层级 */<template><keep-alive :include="cachedViews"><router-view :key="key"/></keep-alive></template><script>export default {// 三级菜单特殊处理方式,如果是三级菜单,父级的name必须是TertiaryMenu,否则无法缓存。同理四级菜单name: 'TertiaryMenu',computed: {cachedViews() {return this.$store.state.tagsView.cachedViews},key() {return this.$route.fullPath}}}</script><style scoped></style>
路由菜单配置示例:
参考文档:https://www.jianshu.com/p/9523bb439950
