Skip to content

Commit

Permalink
缓存
Browse files Browse the repository at this point in the history
  • Loading branch information
gmingchen committed Nov 17, 2023
1 parent 7449656 commit 04f9824
Show file tree
Hide file tree
Showing 12 changed files with 146 additions and 47 deletions.
31 changes: 13 additions & 18 deletions src/components/global/view/index.vue
Original file line number Diff line number Diff line change
@@ -1,28 +1,23 @@
<script setup>
defineProps({
import { cacheHandle } from '@/utils/cache'
const props = defineProps({
// 过度动画 不传则没有动画
transition: {
type: String,
default: () => ''
},
rename: {
type: Boolean,
default: () => false
}
})
const route = useRoute()
const menuStore = useMenuStore()
const tabsStore = useTabsStore()
const keepalives = computed(() => {
const list = []
fo:for (let i = 0; i < tabsStore.tabs.length; i++) {
const tab = tabsStore.tabs[i]
for (let j = 0; j < menuStore.keepaliveMenus.length; j++) {
const menu = menuStore.keepaliveMenus[j]
if (menu.id === tab.menuId) {
list.push(menu.componentName)
continue fo
}
}
}
return list
})
const keepalives = computed(() => menuStore.keepaliveNames)
/**
* 开始进入动画时将父级元素 overflow 设置为空
Expand Down Expand Up @@ -52,13 +47,13 @@ const onLeave = (el) => {
@enter="onEnter"
@leave="onLeave">
<keep-alive :include="keepalives">
<component :is="Component" />
<component :is="rename ? cacheHandle(Component, route) : Component" />
</keep-alive>
</transition>
</template>
<template v-else>
<keep-alive :include="keepalives">
<component :is="Component" />
<component :is="rename ? cacheHandle(Component, route) : Component" />
</keep-alive>
</template>
</router-view>
Expand Down
3 changes: 2 additions & 1 deletion src/router/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -95,12 +95,13 @@ function formatMenus(menus) {
* @returns
*/
function menu2Route(menu) {
const { id, name, type, url, routePath, routeName, redirectName, tab, keepalive, multiple, children } = menu
const { id, name, type, url, routePath, routeName, redirectName, componentName, tab, keepalive, multiple, children } = menu
const meta = {
id: id,
label: name,
type: type,
url: url,
componentName: componentName,
dynamic: true,
tab: tab === 1,
keepalive: keepalive === 1,
Expand Down
14 changes: 11 additions & 3 deletions src/stores/modules/menu.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
import { adminerMenuApi } from '@/api/auth'
import { useTabsStore } from './tabs'
// console.log(useTabsStore())

import { getLoad, setLoad, clearLoad, getMenuAndPermission, setMenuAndPermission, clearMenuAndPermission } from '@/utils/storage'
import { MENU_KEY, PERMISSION_KEY } from '@/utils/constant'
import { MenuType } from '@/utils/enum'
import { parseData2Tree, clearJson } from '@/utils'
import { findKeepaliveName } from '@/utils/cache'

const load = getLoad()
const data = getMenuAndPermission()
Expand All @@ -28,6 +31,7 @@ export const useMenuStore = defineStore('menu', {
url: item.url,
path: item.type === 3 ? `/i-${ item.id }` : item.routePath || (item.url ? `/${ defaultValue }` : ''),
name: item.type === 3 ? `i-${ item.id }` : item.routeName || (item.url ? defaultValue : ''),
componentName: item.componentName,
parentId: item.parentId,
children: []
}
Expand All @@ -45,17 +49,21 @@ export const useMenuStore = defineStore('menu', {
url: item.url,
path: item.type === 3 ? `/i-${ item.id }` : item.routePath || (item.url ? `/${ defaultValue }` : ''),
name: item.type === 3 ? `i-${ item.id }` : item.routeName || (item.url ? defaultValue : ''),
componentName: item.componentName,
parentId: item.parentId,
children: []
}
})
return parseData2Tree(reulst)
},
keepaliveMenus: (state) => {
return state.menus.filter(item => item.keepalive && item.componentName && item.componentName.trim())
const list = state.menus.filter(item => item.keepalive && item.componentName && item.componentName.trim())
return parseData2Tree(list)
},
keepaliveMenuIds: (state) => {
return state.menus.filter(item => item.keepalive && item.componentName && item.componentName.trim()).map(item => item.id)
keepaliveNames: (state, a) => {
// console.log(useTabsStore())
return findKeepaliveName(useTabsStore().tabs, state.keepaliveMenus)
// return useTabsStore().tabs
}
},
actions: {
Expand Down
17 changes: 11 additions & 6 deletions src/stores/modules/tabs.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import router from '@/router'

// todo: ITab value 格式:{a}-{b}-{c}-{d}
// todo: ITab value 格式:{a}&{b}&{c}&{d}
// todo: a: 路由name b: 菜单ID c: 路由query字符串 d: 路由params字符串
// todo: c、d 支持多开的时候需要
const defaultTabs = [{
value: 'home-home-{}-{}',
value: 'home&home&{}&{}',
label: '首页',
name: 'home',
path: '/home',
Expand All @@ -19,22 +19,27 @@ export const useTabsStore = defineStore('tabs', {
active: '',
tabs: []
}),
getters: {},
getters: {
activeTab: (state) => {
const exists = state.tabs.filter(tab => tab.value === state.active)
return exists.length ? exists[0] : {}
}
},
actions: {
/**
* 路由变化事件 设置当前选中、添加标签
* @param {*} route
*/
changeHandle(route) {
const meta = route.meta
let val = `${ route.name }-${ meta.id }`
let val = `${ route.name }&${ meta.id }`
if (meta.tab) {
if (meta.multiple) {
const queryStr = JSON.stringify(route.query)
const paramsStr = JSON.stringify(route.params)
val += `-${ queryStr }-${ paramsStr }`
val += `&${ queryStr }&${ paramsStr }`
} else {
val += `-{}-{}`
val += `&{}&{}`
}
// 如果不存在则添加
if (this.tabs.every(item => item.value !== val)) {
Expand Down
90 changes: 90 additions & 0 deletions src/utils/cache.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
// 缓存
const cacheMap = new Map()

/**
* 根据路由名称、query和params参数 转成组件名称
* @param {*} name 路由名称
* @param {*} query 路由query参数
* @param {*} params 路由params参数
*/
const routeToComponentName = (name, query, params) => {
let result = name
for (const key in query) {
result += `&${ key }=${ query[key] }`
}
for (const key in params) {
result += `&${ key }=${ params[key] }`
}
return result
}
/**
* 根据标签页的value 转成JSON对象
* @param {*} value tab value 值
*/
const tabValueToJson = (value) => {
const values = value.split('&')
const name = values[0]
const query = JSON.parse(values[2])
const params = JSON.parse(values[3])
return { name, query, params }
}
/**
* 根据标签页的value 转成组件名称
* @param {*} value tab value 值
*/
const tabValueToComponentName = (value) => {
const { name, query, params } = tabValueToJson(value)
return routeToComponentName(name, query, params)
}

/**
* 组件缓存处理
* @param {*} component 组件
*/
export const cacheHandle = (component, route) => {
const { name, query, params, meta: { multiple } } = route
if (multiple) {
const key = routeToComponentName(name, query, params)
let cache
if (cacheMap.has(key)) {
cache = cacheMap.get(key)
} else {
cache = {
name: key,
render: () => h(component)
}
cacheMap.set(key, cache)
}
return cache
}
return component
}

/**
* 递归查询需要缓存的组件名称
* @param {*} menus 可以缓存的菜单列表
*/
export const findKeepaliveName = (tabs, menus) => {
const list = []
for (let i = 0; i < menus.length; i++) {
const { id, componentName, multiple, children } = menus[i]
for (let j = 0; j < tabs.length; j++) {
const { menuId, value } = tabs[j]
if (menuId === id) {
let name = componentName
if (multiple) {
name = tabValueToComponentName(value)
}
list.push(name)
}
}
if (children && children.length) {
const arr = findKeepaliveName(children)
if (arr.length) {
componentName && list.push(componentName)
list.push(...arr)
}
}
}
return list
}
14 changes: 7 additions & 7 deletions src/views/layout/components/tabsbar/index.vue
Original file line number Diff line number Diff line change
Expand Up @@ -29,13 +29,13 @@ const removeHandle = (name) => {
onBeforeRouteUpdate((to) => {
tabsStore.changeHandle(to)
const meta = to.meta
if (meta.multiple) {
refresh.value = true
nextTick(() => {
refresh.value = false
})
}
// const meta = to.meta
// if (meta.multiple) {
// refresh.value = true
// nextTick(() => {
// refresh.value = false
// })
// }
})
onBeforeMount(() => {
Expand Down
7 changes: 1 addition & 6 deletions src/views/layout/index.vue
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
<Tabsbar />
</template>
<template #default v-if="!refresh">
<View class="margin-20 flex-item_f-1" transition="left-in-right-out" />
<View class="margin-20 flex-item_f-1" transition="left-in-right-out" rename />
</template>
</component>
<Websocket />
Expand Down Expand Up @@ -49,11 +49,6 @@ const component = computed(() => {
}
return result
})
onMounted(() => {
const instance = getCurrentInstance()
console.log(instance)
})
</script>

<style lang="scss">
Expand Down
2 changes: 1 addition & 1 deletion src/views/modules/develop/menu/index.vue
Original file line number Diff line number Diff line change
Expand Up @@ -282,7 +282,7 @@ onBeforeMount(() => {
<el-form-item label="是否支持tab页签多开(如:用户1的详情页、用户2的详情并存在tab页签)" prop="multiple">
<DictRadio v-model="form.multiple" code="WHETHER" :disabled="readonly" />
</el-form-item>
<el-form-item label="是否支持缓存" prop="keepalive">
<el-form-item label="是否支持缓存(若是路由不设置缓存,但其下的菜单或路由设置了缓存,那么离开这个路由页将不会继续缓存)" prop="keepalive">
<DictRadio v-model="form.keepalive" code="WHETHER" :disabled="readonly" />
</el-form-item>
</template>
Expand Down
4 changes: 3 additions & 1 deletion src/views/modules/nest-router/index.vue
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
<template>
<div class="nest-router">
<div class="nest-router width-300">
<h1>嵌套路由</h1>
<el-input v-model="value" placeholder="输入内容测试页面缓存" />
<el-button @click="jump(1)">路由一</el-button>
<el-button @click="jump(2)">路由二</el-button>
<div class="padding_t-20">
Expand All @@ -11,6 +12,7 @@

<script setup>
defineOptions({ name: 'NestRouter' })
const value = ref('')
const router = useRouter()
const jump = (type) => {
Expand Down
4 changes: 2 additions & 2 deletions src/views/modules/nest-router/modules/router1.vue
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
<template>
<div class="width-300">
<h2>路由一</h2>
<!-- <el-input v-model="value" placeholder="输入内容测试页面缓存" /> -->
<el-input v-model="value" placeholder="输入内容测试页面缓存" />
</div>
</template>

<script setup>
defineOptions({ name: 'Router1' })
defineOptions({ name: 'NestRouter1' })
const value = ref('')
</script>

Expand Down
4 changes: 2 additions & 2 deletions src/views/modules/nest-router/modules/router2.vue
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
<template>
<div class="width-300">
<h2>路由二</h2>
<!-- <el-input v-model="value" placeholder="输入内容测试页面缓存" /> -->
<el-input v-model="value" placeholder="输入内容测试页面缓存" />
</div>
</template>

<script setup>
defineOptions({ name: 'Router2' })
defineOptions({ name: 'NestRouter2' })
const value = ref('')
</script>

Expand Down
3 changes: 3 additions & 0 deletions src/views/modules/user/details/index.vue
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
<template #default>
<div class="user-details-container margin-10 flex flex_w-wrap">
<div class="panel flex-item_f-2 margin-10 padding-30">
<el-input v-model="value" placeholder="输入内容测试页面缓存" />
<div class="flex flex_d-column flex_a_i-center">
<el-avatar
:size="120"
Expand Down Expand Up @@ -95,6 +96,8 @@ defineOptions({
name: 'UserDetails'
})
const value = ref('')
const route = useRoute()
const loading = ref(false)
Expand Down

0 comments on commit 04f9824

Please sign in to comment.