Vue3中如何实现动态菜单递归

全局路由:

export let routerArray = [
    {
        path: '/login',
        component: () => import('@/views/login/index.vue'),
        name: 'login',
        meta:{
            title:'登录',
            hidden: false
        }
    },
    {
        path: '/',
        component: () => import('@/layout/index.vue'),
        name: 'layout',
        meta:{
            title:'总页面',
            hidden: true
        },
        children: [
            {
                path: 'home',
                component: () => import('@/views/home/index.vue'),
                name: 'home',
                meta:{
                    title:'首页',
                    hidden: false
                }
            },
            {
                path: 'ppp',
                component: () => import('@/views/ppp.vue'),
                name: 'ppp',
                meta:{
                    title:'ppp',
                    hidden: false
                }
            }
        ]
    },
    {
        path: '/404',
        component: () => import('@/views/404/index.vue'),
        name: 'Any',
        meta:{
            title:'404',
            hidden: true
        }
    },
    {
        path: '/:pathMatch(.*)*',
        redirect: '/404',
        meta:{
            title:'404',
            hidden: true
        }
    }

] 

pinia的user存储对象:

import { defineStore }  from 'pinia';

import {login} from '@/api/user'

import type{loginDto,resPonseVo} from '@/api/user/type'

import {routerArray} from '@/router/staticRouter.ts'


export let useUserStore=defineStore('User',{
    state: ()=>{
        return {
           token : localStorage.getItem('TOKEN'),
           allRoute:routerArray
        }
    },
    actions:{
      async   userLogin(loginDto1:loginDto){
        let  loginRes:resPonseVo= await login(loginDto1)
        if(loginRes.code==200){
          this.token=(loginRes.data.token as string);
          localStorage.setItem('TOKEN',(loginRes.data.token as string))
        }else{
           return Promise.reject(new Error(loginRes.data.message))
        }
        }
    }
})

 

父组件: 

//父级组件




 

封装的菜单子组件:





这里实现无限嵌套的关键在于最后一个判断,如果是存在子集且大于1时,则引入组件本身,递归循环下去,并且在路由对象中定义了一个meta,里边一个菜单名称,一个是否隐藏,来实现菜单的动态显示

你可能感兴趣的:(web,javascript,vue.js,前端)