3

A dynamic configuration menu is implemented in the vue3 project (add routing dynamically)

1、addRoute

vue3 removes addRoutes and can only use addRoute to add routes, then we need to add them cyclically. All road data is obtained from the background, and the menu is generated directly in a loop, and then we add dynamic routing

addRoute can add routes in the following format, and sub-components can directly add

"data": [{
        "id": 1000,
        "parentId": -1,
        "icon": "iconquanxian",
        "name": "组织架构",
        "path": "/system",
        "component": ()=>import(`@/${url}`), // @/view/framework/Framework.vue
        "redirect": null
        "children": [{
            "id": 1100,
            "parentId": 1000,
            "icon": "iconyonghuguanli",
            "name": "用户管理",
            "path": "/system/user",
            "component": ()=>import(`@/${url}`),
            "redirect": null
        }],

2. Component field problem, unable to dynamically add route, address error.

component field, the problem I encountered, directly configure the'@/' to import into the url, an error will be reported, and the address cannot be identified, so only the splicing method can add the route

3. Refresh routing failure problem

, the data is obtained from the interface, and the problem of routing failure after refresh is solved through next({...to, replace}).

// 路由守卫
let registerRouteFresh = true
router.beforeEach(async (to, from, next) => {
  let res = await api.parentMenu()
  let arr = []
  res.data.data.filter((value, index) => {
    let child = []
    if (value.children && value.children.length) {
      value.children.filter((val, i) => {
        child.push({
          name: val.routeName,
          path: val.path,
          component: () => import(`@/${val.component}`)
        })
      })
    }
    arr.push({
      name: value.routeName,
      redirect: value.redirect,
      path: value.path,
      component: () => import(`@/${value.component}`),
      children: child
    })
  })
  // 如果首次或者刷新界面,next(...to, replace: true)会循环遍历路由,如果to找不到对应的路由那么他会再执行一次beforeEach((to, from, next))直到找到对应的路由,我们的问题在于页面刷新以后异步获取数据,直接执行next()感觉路由添加了但是在next()之后执行的,所以我们没法导航到相应的界面。这里使用变量registerRouteFresh变量做记录,直到找到相应的路由以后,把值设置为false然后走else执行next(),整个流程就走完了,路由也就添加完了。
  if (registerRouteFresh) {
    arr.forEach((value, index) => {
      router.addRoute(value)
    })
    next({...to, replace: true})
    registerRouteFresh = false
  } else {
    next()
  }

image.png
Project address
https://github.com/zxc19890923/vue3-addRoute


张旭超
1.4k 声望222 粉丝

精通 html+div+css jquery, vue, angularjs, angular2, angular4, ionic, ionic2