How many secrets do you not know about vue3 routing

Posted by saloon12yrd on Sun, 06 Mar 2022 09:15:35 +0100


  1. Understanding: a route is a set of key - value s. Multiple routes need to be managed by a router.
  2. Front end Routing: key is the path and value is the component.


In vue, instead of using the regular a tag, we use a custom component router link to create links. This allows Vue Router to change the URL and handle URL generation and encoding without reloading the page. We'll see how to benefit from these features later.


Router view will display the components corresponding to the url. You can put it anywhere to suit your layout.



By calling app Use (router), we can use this in any component$ Access it as router , and use , this$ Access the current route in the form of route #


To access the route in the # setup # function, call the # useRouter # or # useRoute # function. Will we Composition API Learn more in.

Throughout the document, we will often use the "router" instance. Please remember, this$ Router , is exactly the same as using the , router , instance created through , createRouter , directly. We use this$ The reason for router # is that we don't want to import routes into every component that needs to operate routes.

Dynamic route matching with parameters

Many times, we need to map the routes of a given matching pattern to the same component. For example, we might have a User component that should render all users, but the User ID is different. In Vue Router, we can use a dynamic field in the path, which we call {path parameter:

URL s like / users/johnny , and / users/jolyne , now map to the same route.

The path parameter {is represented by colon:. When a route is matched, its params value will be marked with this in each component$ route. The form of params is exposed. Therefore, we can present the current User ID by updating the User's template:



To respond to the change of parameters in the same component, you can simply watch any attribute on the $route} object. In this scenario, it is $route params :

const User = {
  template: '...',
  created() {
      () => this.$route.params,
      (toParams, previousParams) => {
        // Respond to routing changes

Alternatively, use beforeRouteUpdate Navigation guard , it can also cancel navigation:

const User = {
  template: '...',
  async beforeRouteUpdate(to, from) {
    // Respond to routing changes
    this.userData = await fetchUser(

Capture all routes or 404 Not found routes #

General parameters only match the characters between url fragments, separated by /. If we want to match any path, we can use the custom path parameter , regular expression, and add the regular expression in the bracket after the path parameter ,

const routes = [
  // Match everything and put it in ` $route params. Pathmatch ` down
  { path: '/:pathMatch(.*)*', name: 'NotFound', component: NotFound },
  // Match all contents beginning with ` / user - 'and put them in ` $route params. Afteruser ` down
  { path: '/user-:afterUser(.*)', component: UserGeneric },

In this particular scenario, we use between parentheses Custom regular expression , and mark the pathMatch # parameter as Optional repeatable . This is done so that when necessary, we can directly navigate to the route by splitting the path into an array:

  name: 'NotFound',
  params: { pathMatch: this.$route.path.split('/') },

For more information, see Repeat parameter part.

If you are using Historical model , be sure to follow the instructions to configure your server correctly.

Matching syntax of route

Most applications will use static routes such as / about , and dynamic routes such as / users/:userId , as we just mentioned Dynamic route matching But Vue Router can provide more ways!


For simplicity, all routes omit the "component" attribute and only focus on the "path" value.

Customize regular in parameters

When defining parameters like: userId , we internally use the following regular ([^ /] +) (at least one character is not a slash /) to extract parameters from the URL. This works well unless you need to distinguish between two routes based on the content of the parameters. Imagine that two routes /: orderId "and /: productName will match exactly the same URL, so we need a way to distinguish them. The simplest way is to add a static part to the path to distinguish them:

const routes = [
  // Match / o/3549
  { path: '/o/:orderId' },
  // Match / p/books
  { path: '/p/:productName' },

But in some cases, we don't want to add static / o / p # parts. Since orderId is always a number and "productName" can be anything, we can specify a custom rule for the parameter in parentheses:

const routes = [
  // /: OrderID - > match only numbers
  { path: '/:orderId(\\d+)' },
  // /: ProductName - > match anything else
  { path: '/:productName' },

Now go to / 25 to match /: orderId, and others will match /: productName. The order of routes # array is not important!


Make sure to escape the backslash (\), as we did with \ D (becoming \ \ d), and actually pass the backslash character in the string in JavaScript.

Repeatable parameters

If you need to match a route with multiple parts, such as / first/second/third, you should mark the parameters as repeatable with * (0 or more) and + (1 or more):

const routes = [
  // /: chapters - > match / one, /one/two, /one/two/three, etc
  { path: '/:chapters+' },
  // /: chapters - > match /, / one, /one/two, /one/two/three, etc
  { path: '/:chapters*' },

This will provide you with an array of parameters instead of a string, and you need to pass an array when using named routes:

// Given {path: '/:chapters*', name: 'chapters'},
router.resolve({ name: 'chapters', params: { chapters: [] } }).href
// Produce/
router.resolve({ name: 'chapters', params: { chapters: ['a', 'b'] } }).href
// Generate / a/b

// Given {path: '/:chapters+', name: 'chapters'},
router.resolve({ name: 'chapters', params: { chapters: [] } }).href
// An error is thrown because 'chapters' is empty 

These can also be used in conjunction with custom Regularities by adding them after the closing parenthesis:

const routes = [
  // Match numbers only
  // Match / 1, / 1 / 2, etc
  { path: '/:chapters(\\d+)+' },
  // Match /, / 1, / 1 / 2, etc
  { path: '/:chapters(\\d+)*' },

Optional parameters

You can also use? Modifiers (0 or 1) mark a parameter as optional:

const routes = [
  // Match / users and / users/posva
  { path: '/users/:userId?' },
  // Match / users and / users/42
  { path: '/users/:userId(\\d+)?' },

Please note that * technically also indicates that a parameter is optional, but? Parameters cannot be repeated.

Topics: Javascript Front-end Vue.js