How to Correctly Retrieve URL Query Parameters in Vue.js: Understanding the Difference Between $route and $router

Nov 23, 2025 · Programming · 7 views · 7.8

Keywords: Vue.js | URL Query Parameters | Vue Router

Abstract: This article provides an in-depth analysis of common issues when retrieving URL query parameters in Vue.js development. By comparing the differences between $route and $router objects, it explains why using this.$route.query correctly obtains query parameters while this.$router.query causes errors. The article includes comprehensive code examples and references to Vue Router official documentation to help developers deeply understand routing object usage.

Problem Background and Error Analysis

In Vue.js single-page application development, handling URL query parameters is a common requirement. Many developers encounter errors similar to: Uncaught TypeError: Cannot read property 'page' of undefined. This error typically occurs when attempting to retrieve query parameters via this.$router.query.page.

Core Concepts: Difference Between $route and $router

Vue Router provides two important objects: $route and $router, each with distinct functions and purposes:

$route is the currently active route information object, containing parsed information about the current URL. This object is read-only and provides access to the current routing state. Its structure includes the following important properties:

// $route object structure example
{
  path: '/user/',
  query: {
    page: '1'
  },
  params: {},
  hash: '',
  fullPath: '/user/?page=1',
  name: 'userIndex'
}

In contrast, $router is the Vue Router instance, primarily used for programmatic navigation and route control. It provides methods such as push, replace, and go for changing the current routing state.

Correct Method for Retrieving Query Parameters

To correctly retrieve URL query parameters, you should use the $route.query object:

// Correct retrieval method
const currentPage = this.$route.query.page;
console.log(currentPage); // Output: "1"

This approach works because $route.query is specifically designed to store and access URL query parameters. When the URL is websitename.com/user/?page=1, $route.query automatically parses to the {page: "1"} object.

Analysis of Incorrect Usage Examples

A common mistake developers make is confusing the functions of $route and $router:

// Incorrect retrieval method - causes undefined error
const wrongPage = this.$router.query.page; // TypeError: Cannot read property 'page' of undefined

This error occurs because the $router object itself does not have a query property. $router is primarily used for routing navigation operations, such as:

// Correct $router usage example - setting query parameters
this.$router.push({
  name: 'userIndex', 
  query: { page: '123' }
});

Complete Usage Scenario Example

Below is a complete Vue component example demonstrating how to properly handle URL query parameters:

<template>
  <div>
    <p>Current Page: {{ currentPage }}</p>
    <button @click="goToNextPage">Next Page</button>
  </div>
</template>

<script>
export default {
  computed: {
    currentPage() {
      // Correct usage of $route.query to retrieve query parameters
      return this.$route.query.page || '1';
    }
  },
  methods: {
    goToNextPage() {
      // Correct usage of $router.push to set query parameters
      const nextPage = parseInt(this.currentPage) + 1;
      this.$router.push({
        name: 'userIndex',
        query: { page: nextPage.toString() }
      });
    }
  },
  mounted() {
    // Monitor route changes
    this.$watch(
      () => this.$route.query.page,
      (newPage, oldPage) => {
        console.log(`Page changed from ${oldPage} to ${newPage}`);
      }
    );
  }
};
</script>

Difference Between Route Parameters and Query Parameters

Understanding the distinction between route parameters (params) and query parameters (query) is crucial for correctly using Vue Router:

Route Parameters are used to define dynamic segments in route patterns, such as /user/:userId. These parameters are accessed via $route.params:

// Route definition
const routes = [
  {
    path: '/user/:userId',
    name: 'userDetail',
    component: UserDetail
  }
];

// Access in component
const userId = this.$route.params.userId; // For URL: /user/1, returns "1"

Query Parameters are used to pass optional parameters that don't affect route matching, accessed via $route.query:

// For URL: /user/?page=1&sort=name
const page = this.$route.query.page;    // "1"
const sort = this.$route.query.sort;    // "name"

Best Practices and Considerations

In actual development, it's recommended to follow these best practices:

1. Always use $route.query to retrieve query parameters: This is the standard approach designed by Vue Router, ensuring code maintainability and consistency.

2. Handle cases where parameters don't exist: Query parameters might be absent, so provide default values:

const page = this.$route.query.page || '1';
const limit = this.$route.query.limit || '10';

3. Monitor parameter changes: Components should respond when query parameters change:

watch: {
  '$route.query.page'(newPage, oldPage) {
    this.loadData(newPage);
  }
}

4. Type conversion: Query parameters are always strings, so appropriate type conversion is necessary:

const pageNumber = parseInt(this.$route.query.page) || 1;
const isActive = this.$route.query.active === 'true';

Conclusion

Correctly handling URL query parameters in Vue.js requires accurate understanding of the different roles of $route and $router. $route is used for reading current routing state information, including query parameters, while $router is used for controlling route navigation. By using this.$route.query.page instead of this.$router.query.page, developers can avoid common undefined errors and build more stable and maintainable Vue.js applications.

Referencing the Vue Router official documentation for detailed explanations about route objects can provide further insight into other advanced features and best practices of the routing system.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.