Solution to the Problems of Using addRoutes in Vue Project

  • 2021-11-13 06:22:49
  • OfStack

Preface to the table of contents
1. 404 pages
1. Reasons for it
2. Solutions
Step 2 Refresh the white screen
1. Causes
2. Solutions
3. Route duplication
1. Causes
2. Solutions
Summarize

Preface

addRoutes official introduction:

Function signature:

router.addRoutes(routes: Array < RouteConfig > )

Add more routing rules dynamically. Parameter must be an array that meets the requirements of routes option.

When doing vue background authority management system in the past two days, I found that after adding routes with addRoute provided by vue, there will be two bug. Let's see how to solve it ~

1. 404 pages

1. Reasons for it

After adding dynamic routing using addRoutes provided by vue, the route setting on page 404 is no longer at the end of the route

2. Solutions

Add the route of the 404 page to the end of the dynamic route

The code is as follows (example):


// xxx =>  Dynamic routing array that users have 
xxx.push({ path: '*', redirect: '/404', hidden: true })

//  Add routing configuration dynamically 
router.addRoutes(xxx)

Step 2 Refresh the white screen

1. Causes

Dynamic route is not loaded when refreshing

2. Solutions

After the route is added, enter the page

The code is as follows (example):


if( The user's dynamic route is not loaded ){
	//  Resolve the refresh of the white screen bug
  next({
    ...to, // next({ ...to }) Purpose of , Is to ensure that the route is added before entering the page  ( It can be understood as reentry 1 Times )
    replace: true //  Re-advance 1 Times ,  Do not retain repeated history 
  })
} else {
	next()
}

3. Route duplication

1. Causes

Routing settings are added through router. addRoutes (xxx). When exiting, they are not emptied. When logging in again, they are added once again, so there are duplicates.

2. Solutions

The code is as follows (example):


//  Reset route 
export function resetRouter() {
  const newRouter = createRouter()
  router.matcher = newRouter.matcher //  Reset the matching path of the route 
}

This method is to re-instantiate the route, which is equivalent to changing a new route. The route added before does not exist. It is necessary to call 1 when logging out.

Summarize


Related articles: