| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879 |
- import { shallowRef } from 'vue'
- import { AuthType } from '@/constants/menu'
- import { queryAccountMenu } from '@/services/api/account'
- import { defineStore } from '../store'
- import { sessionData } from '../storage'
- export const useMenuStore = defineStore(() => {
- const loading = shallowRef(false)
- const userRoutes = sessionData.getRef('userRoutes')
- // 获取用户路由表
- const getUserRoutes = async () => {
- try {
- loading.value = true
- const res = await queryAccountMenu()
- userRoutes.value = res
- } finally {
- loading.value = false
- }
- }
- // 根据 code 查找对应的子路由
- const getChildrenRoutes = (routeName: string) => {
- const findChildren = (data: Model.UserRoutes[]): Model.UserRoutes[] => {
- for (const item of data) {
- const { code, children } = item
- if (code === routeName) return children ?? []
- if (children) {
- const res = findChildren(children)
- if (res.length) return res
- }
- }
- return []
- }
- return findChildren(userRoutes.value)
- }
- // 过滤菜单
- const filterMenus = (data: Model.UserRoutes[], parentPath = '') => {
- return data.reduce<Model.UserRoutes[]>((pre, cur) => {
- if (!cur.hidden && cur.authType === AuthType.Menu) {
- const routePath = (parentPath ? parentPath + '/' : '') + cur.url
- pre.push({
- ...cur,
- url: routePath,
- children: cur.children ? filterMenus(cur.children, routePath) : [],
- })
- }
- return pre
- }, [])
- }
- // 获取用户菜单(无限级)
- const getUserMenus = (level = 0) => {
- // 过滤层级
- const filterLevel = (data: Model.UserRoutes[], n: number): Model.UserRoutes[] => {
- if (level) {
- return data.map((e) => ({ ...e, children: n <= 1 ? [] : filterLevel(e.children ?? [], n - 1) }))
- }
- return data
- }
- return filterMenus(filterLevel(userRoutes.value, level))
- }
- // 获取子菜单
- const getChildrenMenus = (routeName: string) => {
- const children = getChildrenRoutes(routeName)
- return filterMenus(children)
- }
- return {
- loading,
- userRoutes,
- getUserRoutes,
- getChildrenRoutes,
- getUserMenus,
- getChildrenMenus
- }
- })
|