参数和查询 API

这些函数允许您以编程方式读取和写入参数或历史状态。


getPageParams

检索包含从当前 URL 路径名解析的所有参数的对象。

typescript
function getPageParams<T extends Record<string, string>>(): T

示例

javascript
// Browser location: /projects/marketing/dashboard
// Route pattern: /projects/:category/:tab

import { getPageParams } from '@beforesemicolon/router'

const params = getPageParams()
// Returns: { category: 'marketing', tab: 'dashboard' }

getSearchParams

以键值对象形式检索已解析的 URL 查询参数。支持复杂查询对象的自动JSON解析。

typescript
function getSearchParams<T extends Record<string, string>>(): T

示例

javascript
// Browser location: /search?query=hello&tags=%5B%22js%22%2C%22web%22%5D

import { getSearchParams } from '@beforesemicolon/router'

const query = getSearchParams()
// Returns: { query: 'hello', tags: ['js', 'web'] }

updateSearchQuery

更新或清除 URL 搜索参数。使用历史记录替换就地进行更新(不会向浏览器后堆栈添加新条目)。

typescript
function updateSearchQuery(searchObject: Record<string, unknown> | null): void

示例

javascript
import { updateSearchQuery } from '@beforesemicolon/router'

// Add page parameters to current URL
updateSearchQuery({ page: 2, filter: 'active' })
// Browser updates to: ?page=2&filter=active

// Clear queries
updateSearchQuery(null)
// Browser updates to: (query parameters removed)

getPageData

检索当前历史状态有效负载对象。

typescript
function getPageData<T extends Record<string, unknown>>(): T

示例

javascript
import { getPageData } from '@beforesemicolon/router'

const data = getPageData()
console.log('User Role:', data.role)
编辑此文档