Skip to content

parseQuery Function | Vue Router

parseQuery is a utility function that parses a query string into a LocationQuery object. It handles various query string formats and provides consistent parsing behavior. 🔍

📋 Function Signature

typescript
function parseQuery(search: string): LocationQuery

🎯 Purpose and Usage

The parseQuery function converts URL query strings into structured objects that Vue Router can work with. It's used internally by the router but can also be useful for custom query handling.

Key Features:

  • Query String Parsing - Converts "?key=value" to
  • Array Support - Handles multiple values for same parameter
  • Type Safety - Returns properly typed LocationQuery object
  • Consistent Behavior - Matches Vue Router's query handling

🔍 Parameters

  • Type: string
  • Description: The query string to parse (with or without leading "?")

The function accepts query strings in these formats:

  • "?key=value&another=param"
  • "key=value&another=param" (without ?)
  • "" (empty string)

💡 Practical Usage Examples

Basic Query Parsing

typescript
import { parseQuery } from 'vue-router'

// Parse query string with leading ?
const query1 = parseQuery('?name=john&age=30')
// Result: { name: "john", age: "30" }

// Parse query string without leading ?
const query2 = parseQuery('name=john&age=30')
// Result: { name: "john", age: "30" }

// Parse empty query string
const query3 = parseQuery('')
// Result: {}

Array Parameter Handling

typescript
// Parse query with array parameters
const query = parseQuery('?tags=vue&tags=router&tags=composition')
// Result: { tags: ["vue", "router", "composition"] }

// Mixed single and array parameters
const mixedQuery = parseQuery('?name=john&tags=vue&tags=router')
// Result: { name: "john", tags: ["vue", "router"] }

Real-World Usage

typescript
// Parse current URL query parameters
function getCurrentQueryParams(): LocationQuery {
  const search = window.location.search
  return parseQuery(search)
}

// Parse and process query parameters
function processSearchQuery(searchString: string): SearchFilters {
  const query = parseQuery(searchString)
  
  return {
    query: query.q as string || '',
    category: query.category as string || 'all',
    page: parseInt(query.page as string || '1'),
    sort: query.sort as string || 'relevance'
  }
}

🔧 Advanced Patterns

Query Parameter Validation

typescript
class QueryValidator {
  static validateParsedQuery(query: LocationQuery): ValidationResult {
    const errors: string[] = []
    
    // Validate page parameter
    if (query.page) {
      const page = parseInt(query.page as string, 10)
      if (isNaN(page) || page < 1) {
        errors.push('Invalid page parameter')
      }
    }
    
    // Validate search term length
    if (query.q && (query.q as string).length > 100) {
      errors.push('Search term too long')
    }
    
    // Validate category exists
    if (query.category && !this.isValidCategory(query.category as string)) {
      errors.push('Invalid category')
    }
    
    return { isValid: errors.length === 0, errors }
  }
  
  private static isValidCategory(category: string): boolean {
    const validCategories = ['tech', 'sports', 'news', 'entertainment']
    return validCategories.includes(category)
  }
}

Query Transformation

typescript
class QueryTransformer {
  // Normalize query parameters
  static normalizeQuery(query: LocationQuery): NormalizedQuery {
    return {
      search: this.getStringParam(query, 'q', ''),
      page: this.getNumberParam(query, 'page', 1),
      limit: this.getNumberParam(query, 'limit', 10),
      sort: this.getStringParam(query, 'sort', 'relevance'),
      filters: this.getFilters(query)
    }
  }
  
  // Remove empty parameters
  static removeEmptyParams(query: LocationQuery): LocationQuery {
    const result: LocationQuery = {}
    
    for (const [key, value] of Object.entries(query)) {
      if (value !== undefined && value !== null && value !== '') {
        if (Array.isArray(value) && value.length > 0) {
          result[key] = value
        } else if (!Array.isArray(value)) {
          result[key] = value
        }
      }
    }
    
    return result
  }
  
  // Merge multiple query objects
  static mergeQueries(...queries: LocationQuery[]): LocationQuery {
    return queries.reduce((result, query) => ({
      ...result,
      ...query
    }), {})
  }
}

💡 Pro Tip: Use parseQuery for consistent query parsing that matches Vue Router's behavior. This ensures your custom query handling works the same way as the router's built-in functionality.

🚀 Vue Router - 让前端路由变得简单而强大 | 构建现代化单页应用的最佳选择