SoFunction
Updated on 2025-04-05

Vue router configuration and usage analysis explanation

illustrate

  1. This tutorial is suitable for the configuration and use of route vue-router@4 in vue3
  2. Installation and configuration
  3. Basic use of routing
  4. Adding dynamic routing
  5. Router Guard
  6. The routing configuration cannot be found (path: ‘/:pathMatch(.)’,)

1. Installation and configuration

Install

npm install vue-router@4

Configuration

//In the router file you createdimport { createRouter, createWebHashHistory } from 'vue-router'
//createWebHashHistory with # when accessing//createWebHistory does not bring # when accessingconst router = createRouter({
  history: createWebHashHistory(),
  routes: [
    //...
  ],
})
export default router
//In the fileimport router from 'router_path'
const app = createApp(App)
(router)
('#app')

2. Use in html

Creating a single-page application with Vue + Vue Router is very simple: through , we have composed our application with components. When joining Vue Router, all we need to do is map our components to the routes and let Vue Router know where to render them. Here is a basic example:

HTML

<script src="/vue@3"></script>
<script src="/vue-router@4"></script>
<div >
  <h1>Hello App!</h1>
  <p>
    <!--use router-link Components for navigation -->
    <!--By passing `to` To specify the link -->
    <!--`<router-link>` Will render a correct one `href` Attributes `<a>` Label-->
    <router-link to="/">Go to Home</router-link>
    <router-link to="/about">Go to About</router-link>
  </p>
  <!-- Routing exit -->
  <!-- The component that the route matches will be rendered here -->
  <router-view></router-view>
</div>

router-link

Note that instead of using the regular a tag, we use a custom component router-link to create the link. This allows Vue Router to change URLs without reloading the page, handle URL generation and encoding. We will see later on how to benefit from these features.

router-view

router-view will display the components corresponding to url. You can put it anywhere to fit your layout.

3. Basic use of routing

The basic elements of the routing include name, path, component, and meta (dictionary)

  • name route name
  • path route path
  • component component name (component path and component name)
  • meta-routing meta information
  • example
import { createRouter, createWebHashHistory } from 'vue-router'
import Login from '@/views/'
const router = createRouter({
  history: createWebHashHistory(),
  routes: [
    {
      path: '/',
      name: 'login',
      meta:{
        title:'Log in',
      },
      component: Login
    },
})
export default router

Routing match with parameters

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

const User = {
  template: '<div>User</div>',
}
// These will be passed to `createRouter`const routes = [
  // Dynamic fields start with a colon  { path: '/users/:id', component: User },
]

URLs like /users/johnny and /users/jolyne are now mapped to the same route.

Path parameters are represented by colon:. When a route is matched, its params value will be exposed in each component as this.$. Therefore, we can render the current user ID by updating the User's template:

const User = {
  template: '<div>User {{ $ }}</div>',
}

You can set multiple path parameters in the same route, which will be mapped to the corresponding fields on $. For example:

Matching mode Match paths
/users/:username /users/eduardo { username: ‘eduardo’ }
/users/:username/posts/:postId /users/eduardo/posts/123 { username: ‘eduardo’, postId: ‘123’ }

In addition to r o u t e . p a r a m s , the route object also discloses other useful information, such as r o u t e . q u e r y (if a parameter exists in U R L), (if a parameter exists in URL), (if a parameter exists in URL), etc. You can view the full details in the API reference.

4. Adding dynamic routing

Router Guard

The routing configuration cannot be found

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

const routes = [
  // Will match everything and put it under `$`  { path: '/:pathMatch(.*)*', name: 'NotFound', component: NotFound },
  // Match everything starting with `/user-` and place it under `$`  { path: '/user-:afterUser(.*)', component: UserGeneric },
]

In this particular scenario, we use a custom regular expression between brackets and mark the pathMatch parameter as optionally repeatable. This is done so that we can directly navigate to the route by splitting the path into an array when we need it:

this.$({
  name: 'NotFound',
  // Keep the current path and delete the first character to avoid the target URL starting with `//`.  params: { pathMatch: this.$(1).split('/') },
  // Keep existing queries and hash values, if any  query: this.$,
  hash: this.$,
})

This is the end of this article about the analysis and explanation of Vue router configuration. For more related Vue router configuration content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!