Table of Contents
1. Define routes with parameters
2. Get routing parameters in the component
3. Optional parameters and wildcard characters
Optional parameters
Wildcard
4. Several ways to jump with parameters
Using router-link
Programming Navigation
Home Web Front-end Vue.js How to use route parameters in vue router?

How to use route parameters in vue router?

Sep 16, 2025 am 07:20 AM

The core of using routing parameters in Vue Router is to capture URL values ​​through dynamic snippets. 1. When defining routes with parameters, use colons in the path: represent dynamic parameters, such as /user/:id; 2. In the component, the parameters can be obtained through $route.params, and useRoute can be used in Vue 3; 3. Optional parameters are added?, and the wildcard character uses * to capture unmatched paths; 4. For jumps, you can use router-link or programmatic navigation and explicitly pass params.

Use routing parameters in Vue Router, the core is to capture the values ​​in the URL through dynamic snippets. For example, 123 in /user/123 can be passed to the component as a parameter.


1. Define routes with parameters

When defining a route, you can use colon : in the path to represent a dynamic parameter. For example:

 const routes = [
  {
    path: '/user/:id',
    component: UserDetail
  }
]

In this way, when accessing /user/123 or /user/abc , the UserDetail component will be matched, and 123 or abc will be passed in as parameters.

Note: You can define multiple parameters, such as /user/:id/post/:postId , but it is generally recommended to keep the path simple.


2. Get routing parameters in the component

Inside the component, you can get these parameters through $route.params . For example:

 <template>
  <div>User ID: {{ userId }}</div>
</template>

<script>
export default {
  data() {
    return {
      userId: this.$route.params.id
    }
  }
}
</script>

If you are using the Vue 3 Composition API, you can use useRoute :

 import { useRoute } from &#39;vue-router&#39;

export default {
  setup() {
    const route = useRoute()
    return {
      userId: route.params.id
    }
  }
}
</script>
  • The parameters are responsive, but modifying the URL will not trigger component re-rendering, it will only update the $route object.
  • If you want to do certain operations based on parameter changes, remember to listen for changes in $route .

3. Optional parameters and wildcard characters

Vue Router also supports optional parameters and wildcards, two features that are very useful when handling flexible paths.

Optional parameters

Add a ? after the parameter to indicate that this parameter is optional:

 {
  path: &#39;/search/:query?&#39;,
  component: SearchResults
}

In this way, both /search and /search/vue can match the same component.

Wildcard

If you want to capture all unmatched paths, you can use * :

 {
  path: &#39;/:pathMatch(.*)*&#39;,
  component: NotFound
}

This way of writing will split the path into an array, for example, accessing /foo/bar/baz , $route.params.pathMatch will be [&#39;foo&#39;, &#39;bar&#39;, &#39;baz&#39;] .


4. Several ways to jump with parameters

You can use <router-link> or programmatic navigation to jump to the page with parameters.

 <router-link :to="`/user/${userId}`">View the user</router-link>

Or a little more structured:

 <router-link :to="{ path: &#39;/user/&#39; userId }">View user</router-link>

Programming Navigation

 this.$router.push(`/user/${userId}`)

Or use object form:

 this.$router.push({ name: &#39;user&#39;, params: { id: userId } })

Note: When using params , if a named route is used, the parameters in the path will not be automatically spliced, and params must be explicitly provided.


Basically that's it. The routing parameters themselves are not complicated, but in actual projects, it is easy to cause problems due to improper path design or inadequate parameter processing. Especially when nested routes and named routes are present, special attention should be paid to the parameter passing method.

The above is the detailed content of How to use route parameters in vue router?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

ArtGPT

ArtGPT

AI image generator for creative art from text prompts.

Stock Market GPT

Stock Market GPT

AI powered investment research for smarter decisions

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

How to set the page title dynamically for each route in Vue.js? How to set the page title dynamically for each route in Vue.js? Sep 21, 2025 am 03:19 AM

Answer: In Vue.js, page title can be set dynamically through VueRouter's meta field and navigation guard. 1. Define meta.title for each route and update document.title in router.afterEach; 2. If the title depends on asynchronous data, it can be retrieved and updated in the component; 3. Vue3 can create usePageTitle combination function multiplexing logic; 4. For SEO-sensitive scenarios, SSR should be supported using @vueuse/head and other libraries.

How to use route parameters in vue router? How to use route parameters in vue router? Sep 16, 2025 am 07:20 AM

The core of using routing parameters in VueRouter is to capture URL values ​​through dynamic fragments. 1. When defining routes with parameters, use colons in the path to represent dynamic parameters, such as /user/:id; 2. In the component, parameters can be obtained through $route.params, useRoute can be used in Vue3; 3. Optional parameters are added?, and wildcards use * to capture unmatched paths; 4. Jumps can be used to use router-link or programmatic navigation and explicitly pass params.

What is the difference between Vue.set (or this.$set) and direct assignment? What is the difference between Vue.set (or this.$set) and direct assignment? Sep 15, 2025 am 01:26 AM

In Vue2, direct assignment cannot trigger responsive updates, while Vue.set or this.$set can ensure that new attributes or array items are correctly detected and updated. 2. Vue3 uses Proxy to implement comprehensive responsive listening, supporting dynamic addition of attributes and array index modifications, so direct assignment can trigger updates without using $set; 3. Although $set still exists in Vue3 to be compatible with old code, it has been deprecated. It is recommended to use direct assignment or replace the entire object/array to ensure responsiveness. This scheme is valid in both versions.

How to listen to native DOM events on a Vue.js component? How to listen to native DOM events on a Vue.js component? Sep 16, 2025 am 08:04 AM

In Vue3, native DOM events are directly bound to the component root element by default, without the .native modifier; if the component is a single element, you can directly listen with @event, such as @click; for multiple nodes or explicit control, custom events should be defined and triggered through $emit or defineEmits to maintain cross-version compatibility and a clear event interface.

How to handle component lifecycle in the Vue 3 Composition API? How to handle component lifecycle in the Vue 3 Composition API? Sep 17, 2025 am 07:33 AM

In Vue3's Composition API, the life cycle hook is used by the onX function. The answer is: 1. Import onMounted, onUpdated, onUnmounted and call it in setup(); 2. Setup() replaces created, without separate definition; 3. Life cycle logic can be encapsulated in a combined function to achieve reuse; 4. The hook must be called synchronously and can be registered multiple times; 5. Common uses include obtaining data during mount and cleaning resources during uninstallation, thereby improving code organization and maintainability.

How to handle assets like images and fonts in a Vue.js project with Vite? How to handle assets like images and fonts in a Vue.js project with Vite? Sep 20, 2025 am 02:45 AM

Placestaticassetslikeimagesandfontsinthepublicdirectoryfordirectaccessorinsrc/assetsforbundledprocessing.2.ImportimagesincomponentsusingscriptsetupforautomaticURLresolution.3.Definecustomfontsvia@font-faceinCSSwithaliasedpaths,ensuringViteresolvesthe

How to create a custom v-model on a Vue component? How to create a custom v-model on a Vue component? Sep 21, 2025 am 01:08 AM

To create a custom v-model in Vue3, you need to define the modelValue property and emitupdate:modelValue event; 2. You can specify the custom prop name through v-model:title; 3. Vue2 uses value and input events by default, but you can change it to modelValue and update:modelValue to be compatible with Vue3; 4. Always declare emits in Vue3 to ensure clarity and verification; 5. Avoid directly modifying the prop, and updates should be triggered through events, so that the component supports two-way binding like native input.

How to set up a new project with the Vue CLI or Vite for Vue.js? How to set up a new project with the Vue CLI or Vite for Vue.js? Sep 16, 2025 am 06:45 AM

Use VueCLI or Vite to quickly build Vue.js projects. 2. VueCLI is based on webpack and has rich features and is suitable for projects that require deep plug-in integration. 3.Vite starts faster, supports hot updates, and is recommended for new projects. 4. Most new projects choose Vite because of its superior performance and simple configuration.

See all articles