Vue-Router(4) 学习之动态路由二

1. 动态路由表 dynamic_routes


export const dynamic_routes = [
  {
    path: '/origin_setting',
    component: Layout,
    redirect: '/origin_setting/index',
    depthFlagArr: [0,1],
    name: 'MyOriginSetting',
    children: [
      {
        path: '/origin_setting/index',
        name: 'OriginSetting',
        meta: { title: '域名管理', icon: Setting },
        component: () => import('../views/OriginSetting/index.vue')
      }
    ]
  },
  {
    path: '/avatar-manage',
    component: Layout,
    redirect: '/avatar-manage/index',
    // depthFlagArr: [],
    show_ivl_menu: true,
    name: 'MyAvatarManage',
    children: [
      {
        path: '/avatar-manage/index',
        name: 'AvatarManage',
        meta: { title: '形象管理', icon: Avatar },
        component: () => import('../views/AvatarManage/index.vue')
      }
    ]
  }
];

说明:depthFlagArr,show_ivl_menu 是判断是否加载路由的标识

2. 路由控制 private_routes.ts

使用pinia作为全局store,控制包括路由权限、userinfo、token等动态信息
 

// private_routes.ts 路由控制
import { defineStore } from 'pinia'
import { computed } from 'vue';
import router from '@/router'

import { useAuthStore } from '@/store/user'
import { dynamic_routes } from '@/router/menuRoutes'
// 动态路由菜单
export const useDynamicMenuStore = defineStore('dynamicRouter', () => {
  const userStore = useAuthStore()
  const _id = computed(() => userStore.info._id)
  const depth = computed(() => userStore.info.depth)
  const show_ivl_menu = computed(() => userStore.info.show_ivl_menu)
  const menuRoutes = computed(() => {
    console.log(_id.value)
    if (!_id.value) return []
    // 使用computed根据role筛选对应路由
    return dynamic_routes.filter(route => {
      if (route.depthFlagArr && route.depthFlagArr.includes(depth.value))  {
        router.addRoute(route) // Add the route to 
        return true;
      } else if(route.show_ivl_menu && show_ivl_menu.value) {
        router.addRoute(route) // Add the route to 
        return true;
      }
    })
  })

  return { _id, menuRoutes }
});

3. 菜单栏

显示在左侧的导航栏






4. 问题思考

        4.1 动态路由刷新404

        4.2 动态路由与userInfo的关系

你可能感兴趣的:(vue.js,学习,javascript,vue)