VueRouter Basic tutorial series 🎉

Introduction to the

  • Inspired by its own path matching syntax, the Vue Router supports multiple advanced matching modesexpress.
  • Static Route supports only full matching based on the address. Dynamic Routing supports multiple advanced matching modes in addition to full matching.

The path parameter

Dynamic Routing has path parameters in its path addresses, allowing it to map one or more matching addresses to the same component according to a given matching pattern.

Components that are mapped to dynamic routes can be understood as component templates (which can be hit by multiple paths that match patterns, unlike static routes that have a one-to-one relationship).

In real-world scenarios, for example, user information based on different user ids would be rendered in the same user component. It is not possible to define multiple routing addresses for different ids, such as /user/100 and /user/101.

So what does a dynamic routing address with a path parameter look like? Here’s a simple example:

{path:'/users/:id'.component: {name:"Users".template:'<p>{{$route.params.id}}</p>'}}

// */users/1001 -> this.$route.params.id -> 1001
Copy the code

The format of the path parameter is :[pathParam], where pathParam is the path parameter name, which will be used as the key of the matching content, and finally saved in the form of key-value pair $route.params.

Path parameters and regular expressions

You can use regular expressions for path parameters to obtain stronger matching capabilities. This is done by writing a concrete regular expression in the parenthesis following the path argument:

{
    path:'/user-:userName(.*)'.component: {name:'Users'.template:'<h1>{{$route.params.userName}}</h1>'}}// */user-John -> this.$route.params.userName -> John.
Copy the code
{
    path:'/user-:userName(.*)/:userId'.component: {name:'Users'.template:'<h1>{{$route.params.userName}} | {{$route.params.userId}}</h1>'}}// */user-Alice/123 -> this.$route.params.userName -> Alice | 123
Copy the code

/user-:userName(.*) = /user-:userName(.*) = /user-(.*) = /user-(.*)

Now let’s go back to ordinary “path arguments” such as /:id, which are actually internally reged-based. For example, /:id is converted to a regular expression by ([^/]+) (matches at least one character that does not end in a /), $route.param.id = $route.param.id = $route.param.id = $route.param.id = $route.param.

Pay attention to escape symbols

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

Path parameters and wildcards

Path parameters can also be associated with some common wildcards? , +, and * are used to control the number of repetitions of path segment matching.

For a better understanding of the definition of a path segment, I define each part of the path that is split with/as a path segment.

The wildcard instructions
? This can be repeated 0 or 1 times
* This can be repeated 0 or N times
+ This can be repeated 1 or n times

VueRouter stores the path fragments that are repeatedly matched into an array.

{
    path:'/user-:userInfo(.*)*'.component: {name:'UserInfo'.template:'<h1>{{$route.params.userInfo[1]}} | {{$route.params.userInfo[2]}}</h1>'}}// */user-Alice/1001 -> this.$route.params.userInfo -> ['Alice', '1001']
Copy the code

Due to the? The wildcard represents zero or more, so in practice it is no different than a normal path parameter match. The parameter may be zero, so it is not saved as an array.

404 Route Configuration

Of course, path wildcards are more commonly used to capture all routes or in 404-NotFound scenarios.

 {path:'/:notFound(.*)*'.component: {name:'404'.template:'Not Found Page'}}
Copy the code

Dynamic routing and component updates

In dynamic routing, a component is often associated with multiple paths that match the matching pattern. Vue to reduce the performance cost of reusing component instances, when the next route matches a component instance that has already been created, the component instance is reused.

The most obvious problem with reusing component instances is that the component’s one-off lifecycle hooks (e.g. created, Mounted, etc.) are no longer triggered.

There are two ways to listen for route changes in a component instance that is being reused to perform the logic:

  • use$watchListening to the$routeObject.
  • routablebeforeRouteUpdateHook.
{
    created(){
        this.$watch(() = >this.$route.params),
        (newData, oldData) = >{
            // Perform the corresponding operation.}},beforeRouteUpdate(to, from){
        // Perform the corresponding operation.}}Copy the code

Pay attention to

Dynamic routing must ensure that the routing address is successfully matched. Only matching addresses are captured by the regex group, and the matching value is saved to $route.params.

Observe the following matches:

{
    path:'/user/:id(\\d+)*' 
}

// '/user/123' ✔️, group value ['123']
// '/user/123/456' ✔️, group values ['123', '456']
/ / '/ user / 123 / ABC' x,
/ / / user/ABC/efg 'x'
Copy the code