SoFunction
Updated on 2025-04-10

Practical record of Vue router application problems

Preface

This article records some problems encountered by vue-router of vue2 during use.

Problem record

Application of route guard

Depending on the location of the route guard binding, there are three types of route guards below

Global Guard

beforeEach/beforeResolve/afterEach

Route exclusive guard

beforeEnter

Guards within components

beforeRouteEnter/beforeRouteUpdate/beforeRouteLeave

The complete navigation analysis process, read the official documentation, as follows:

Navigation is triggered.

Call the beforeRouteLeave guard in the inactivated component.

Call the global beforeEach guard.

Call the beforeRouteUpdate guard (2.2+) in the reused component.

Call beforeEnter in the routing configuration.

Resolve asynchronous routing components.

Call beforeRouteEnter in the activated component.

Call the global beforeResolve guard (2.5+).

Navigation is confirmed.

Calls the global afterEach hook.

Triggers DOM update.

Use the created instance to call the callback function passed to next in the guard beforeRouteEnter.

The following are some practical application scenarios for commonly used hooks:

beforeRouteLeave: Before jumping to the page, remind the user whether to save the information, or automatically save the draft for the user.

beforeEach: determine whether to log in, whether you have permissions, etc., do operations such as jump login, apply for permissions, and process permission menus.

beforeRouteUpdate: When re-entering the same page, re-initialize and load data.

beforeRouteEnter: Get the information of the previous page of the current page. For example, when we are on the login page, we need to redirect to the previous page after logging in, and we can obtain it through this hook. Note: Here, no! able! Get component instance this, because the new component has not been created yet. However, you can pass a callback to next to access the instance, and it will be executed after the instance is created.

beforeRouteEnter (to, from, next) {
  next(vm => {
    // Access component instances through `vm`  })
}

Several other route guards are not commonly used by me. Anyone with additional supplements are welcome to leave comments.

Dynamic routing implements permission control

Application scenario: The management side needs to display different menu bars according to different permissions, and hopes that users without permission will not be able to access certain pages.

Solution: Before entering the route, we intercept, first determine whether the page permission needs to be processed, and then determine whether the permission has been processed. If the answers are all "yes", we do not need to process it. Otherwise, request the interface, obtain the permission menu of the current user, and dynamically add routes to the router based on the information returned by the background, and then re-enter the route (avoiding the intercepted access is a newly added route, which causes the problem of inaccessibility).

For details, see the pseudocode below:

((to, from, next) => {
    if (needAuthority()) {  //Pages that do not require judgment of permissions will not be processed      next()
      return
    } 
    if (alreadyGetAuthorityMenu) {  //The permission menu has been processed and will not be processed anymore        next()
        return
    }
  
    handleAuthority().then(()=>{
        next({ ...to, replace: true })  //The permission menu interface is successfully processed, dynamic routing has been added, re-enter the routing      }).catch(() => {
        ('Request permission menu interface error')
        next()
    })
})

We did these things in handleAuthority

  • Determine whether you have permissions. Users who do not have permissions will jump to the permission application page
  • According to the permission list transmitted from the background, use the (routes: Array) API to dynamically add the route corresponding to the pages that require permission control to the router.
  • Add a guarantee page to the router dynamically, which can be a page that prompts that there is no permission, or a simple 404 page.

It should be noted that after dynamically adding the route, you need to re-enter the route ({ ...to, replace: true }) if the intercepted page route is the route you added later, then the new route will not be accessible.

The routing parameters of hash mode are interfered with

Application scenarios: For example, if the WeChat sharing link is added, parameters such as '?from=singlemessage&isappinstalled=0' are added. When we use hash mode routing and pass parameters in params, we will often be interfered by external parameters, resulting in the page being inaccessible or the parameters being not available. Using dynamic routing parameters is a better choice.

const router = new VueRouter({
  routes: [
    // Dynamic path parameters begin with a colon    { path: '/user/:id', component: User }
  ]
})
const userId = '123'
// Two jump methods({ name: 'user', params: { userId }}) // -> /user/123
({ path: `/user/${userId}` }) // -> /user/123
// The params here do not take effect({ path: '/user', params: { userId }}) // -> /user

Going further, we can use props to decouple the component and route, define the id props in the component, and get the passed parameters.

const router = new VueRouter({
  routes: [
    { path: '/user/:id', component: User, props: true }
  ]
})

Jump the same component route, not refresh?

Application scenario: Jump the page of the same component, but the parameters are different, and I hope to refresh the page.

Solution: We can re-execute the code to be executed in beforeRouteUpdate, but if all variables need to be initialized, there will inevitably be omissions. The simpler way is to listen for route changes, and the change is this.$(0) refresh.

// recommendbeforeRouteUpdate(to, from, next) {
    // Reload data    next();
},
watch: {
 '$route'(to, from) {
    this.$(0)
 }
}

Summarize

This is all about this article about Vue router application issues. For more related Vue router application issues, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!