SoFunction
Updated on 2025-04-05

Vue router dynamic routing setting parameters optional problem

In daily work, we need to map all the matched routes to a component.

The effect you want to achieve as follows:

If the page and id are not passed, it will be mapped to the user default list page.

Pass page and id, display different pages according to page

question

The above effects cannot be achieved using the following code snippets, because by default, the page and id parameters are required. If the parameters are not passed, they will jump to the home page according to the default route.

new Router({
  routes: [
    {
      path: '/user/:page/:id',
      name: 'User',
      component: () => import('pages/user')
    },
    {
      path: '*',
      redirect: '/home'
    }
  ]
})

Solution

Change the parameter configuration to optional

path: '/user/:page?/:id?'

ps: Let's take a look at the dynamic addition of vue-router.

Dynamically adding routes can be used for permission management. After logging in, the server returns to the permission menu, and dynamically add routes to the front end. Then in the settings menu

1. vue-router has a method(routes)Dynamically add more routing rules. The parameters must be an array that meets the routes option requirements.

How to use

this.$[0].({//Insert the route name:'list',
 path: 'list',
 component: resolve => require(['../template/'], resolve)//Bring components in with require});
this.$(this.$);//CalladdRoutesAdd a route

My routing file:

export default new Router({
 routes: [
  {
   path: '/',
 
   component: index,
  },
  {
   path: '/login',
   name: 'login',
   component: login
  }
 ]

Summarize

The above is the optional vue router dynamic routing parameter setting that the editor introduced to you. I hope it will be helpful to you. If you have any questions, please leave me a message. The editor will reply to you in time!