Route Parameters

In VitePress's static site generation architecture, the URL structure serves as the primary entry point for users accessing documentation. Beyond standard hierarchical directories, VitePress provides a powerful dynamic routing mechanism that allows locating specific content via parameters within the URL. This mechanism is commonly referred to as "Route Parameters." When a user inputs a path containing parameters into their browser address bar, such as https://example.com/docs/guide/advanced, the part of the URL labeled advanced constitutes the route parameter. VitePress parses these parameters and maps them to corresponding page templates or content blocks, thereby achieving dynamic rendering.

Route parameters primarily fall into two categories: Query Parameters and Path Parameters. Although they differ in their representation within a URL, both are parsed and processed through identical mechanisms in VitePress's source implementation. Path parameters typically appear within the path string itself (e.g., /docs/:slug), whereas query parameters reside after the path (e.g., ?id=123). Understanding the distinction between these two is crucial for building flexible documentation navigation systems.

Dynamic Page Generation Based on Path Parameters

VitePress supports dynamically rendering page content through path parameters, which serves as a key feature for implementing custom document structures. When configuration files define routes with path parameters, VitePress extracts these parameters during the build phase and injects them into the corresponding templates at runtime.

To implement this functionality, developers must define routing rules within vitepress.config.js. Below is a typical configuration example:

module.exports = {
  // ...other configurations
  routes: [
    {
      // Use :slug as the path parameter to capture dynamic parts of the URL.
      // Example usage: /docs/my-page/:slug
      path: '/docs/:slug',
      // Define the page template file corresponding to this route.
      file: 'guide/index.vue',
      // Optional: Define default content to display when no specific slug matches.
      content: {
        title: 'Documentation Center',
        body: `
          <p>This is a generic documentation center page.</p>
          <ul>
            <li><a href="/docs/my-page/advanced">Advanced Guide</a></li>
            <li><a href="/docs/my-page/basic">Basic Introduction</a></li>
          </ul>
        `
      }
    },
    {
      // Directly points to a specific file without requiring parameter matching.
      path: '/docs/my-page/advanced',
      file: 'guide/advanced.vue'
    }
  ]
}

In the configuration above, the first route definition establishes a general capture rule. When a user accesses /docs/my-page/anything, VitePress extracts anything as the parameter value. If no specific file corresponds to this path, the system attempts to render the default content from the guide/index.vue template and passes the parameters into the template context for usage.

Using Route Parameters in Templates

Once route parameters are successfully parsed and injected into the context, developers can reference them within page templates. VitePress provides convenient syntax to access these parameters, typically through $page.frontmatter or specific global objects.

Assume we write a list component in guide/index.vue intended to display dynamically generated document links. We could handle this as follows:

<template>
  <div class="dynamic-params-demo">
    <h1>{{ page.title }}</h1>
    
    <!-- Check if specific route parameters exist -->
    <div v-if="hasParam('slug')">
      <p>The slug for the current document is: <strong>{{ param('slug') }}</strong></p>
      <p>This allows us to dynamically adjust page titles or content based on the URL.</p>
    </div>

    <!-- Render default content -->
    <ul class="doc-links">
      <li v-for="(link, key) in links" :key="key">
        <a :href="`/docs/my-page/${link.slug}`">{{ link.title }}</a>
      </li>
    </ul>
  </div>
</template>

<script>
export default {
  data() {
    return {
      links: [
        { title: 'Advanced Guide', slug: 'advanced' },
        { title: 'Basic Introduction', slug: 'basic' }
      ]
    }
  },
  methods: {
    // Retrieve the value of a specific parameter.
    param(key) {
      return this.$page.params[key] || ''
    },
    // Determine if a parameter exists.
    hasParam(key) {
      return !!this.$page.params[key]
    }
  }
}
</script>

In this example, we use the $page.params object to access route parameters. When a user directly accesses /docs/my-page/advanced, param('slug') returns the string 'advanced'; conversely, when accessing the default route /docs/my-page/something-else, it correctly extracts something-else. This mechanism enables pages to automatically adjust displayed content based on URL changes without modifying the template code itself.

Collaboration with Query Parameters

In addition to path parameters, VitePress also supports passing data via query strings. In practical applications, path and query parameters often need to work together to provide a complete user experience. For instance, a document detail page may require knowing both the title of the current document (via path parameter) and its ID (via query parameter).

At the configuration level, query parameters typically do not require special route definitions; they are automatically appended to existing routes. However, accessing them in templates involves slightly different syntax: Query parameters can be retrieved via the $page.query object as shown below:

export default {
  methods: {
    // Retrieve a query parameter value.
    getQuery(key) {
      return this.$page.query[key] || ''
    }
  }
}

By combining path parameters and query parameters, developers can construct highly flexible documentation systems. For example, multiple content blocks of different themes could be displayed on the same page, with each block's visibility controlled by distinct URL parameters. This combination capability significantly expands VitePress' potential in content management, allowing it to support complex interaction logic beyond simple stacking of static pages.

Best Practices and Considerations

Adhering to best practices when using route parameters ensures site stability and maintainability. First, avoid overly broad routing rules that could lead to unexpected redirects or content confusion. Second, always explicitly specify the file attribute in configuration files; otherwise, VitePress may attempt to match default content, potentially increasing performance overhead.

Furthermore, pay attention to escaping issues when handling special characters. If route parameters contain spaces or other symbols, URLs automatically encode them (e.g., %20). Therefore, care must be taken when directly concatenating URLs within templates. Finally, it is recommended to implement validation logic for critical route parameters to ensure input values conform to expected formats, thereby enhancing the robustness of frontend pages.

By reasonably utilizing path and query parameters, VitePress can construct flexible yet efficient documentation site architectures capable of meeting various complex content display requirements.