Skip to content

useUrlSearchParams

类别
导出体积
1.3 kB
上次更改
3 days ago

响应式 URLSearchParams

示例

  • foo=bar
  • vueuse=awesome

用法

js
import { useUrlSearchParams } from '@vueuse/core'

const params = useUrlSearchParams('history')

console.log(params.foo) // 'bar'

params.foo = 'bar'
params.vueuse = 'awesome'
// URL 更新为 `?foo=bar&vueuse=awesome`

哈希模式

当在哈希模式路由中使用时,将 mode 设置为 hash

js
import { useUrlSearchParams } from '@vueuse/core'

const params = useUrlSearchParams('hash')

params.foo = 'bar'
params.vueuse = 'awesome'
// URL 更新为 `#/your/route?foo=bar&vueuse=awesome`

哈希参数

当在历史模式路由中使用,但想要使用哈希作为参数时,将 mode 设置为 hash-params

js
import { useUrlSearchParams } from '@vueuse/core'

const params = useUrlSearchParams('hash-params')

params.foo = 'bar'
params.vueuse = 'awesome'
// URL 更新为 `/your/route#foo=bar&vueuse=awesome`

类型声明

typescript
export type UrlParams = Record<string, string[] | string>
export interface UseUrlSearchParamsOptions<T> extends ConfigurableWindow {
  /**
   * @default true
   */
  removeNullishValues?: boolean
  /**
   * @default false
   */
  removeFalsyValues?: boolean
  /**
   * @default {}
   */
  initialValue?: T
  /**
   * 自动写回到 `window.history`
   *
   * @default true
   */
  write?: boolean
  /**
   * Write mode for `window.history` when `write` is enabled
   * - `replace`: replace the current history entry
   * - `push`: push a new history entry
   * @default 'replace'
   */
  writeMode?: "replace" | "push"
}
/**
 * 响应式 URLSearchParams
 *
 * @see https://vueuse.org/useUrlSearchParams
 * @param mode
 * @param options
 */
export declare function useUrlSearchParams<
  T extends Record<string, any> = UrlParams,
>(
  mode?: "history" | "hash" | "hash-params",
  options?: UseUrlSearchParamsOptions<T>,
): T

源码

源码演示文档

贡献者

Anthony Fu
一纸忘忧
lstoeferle
Fernando Fernández
Ivan Shakhorski
Huodoo
Anthony Fu
sun0day
专业逮虾户aa
Marius
Patrick Stillhart
odex21
Michel EDIGHOFFER
Alex Kozack

更新日志

v12.4.0 on 1/10/2025
dd316 - feat: use passive event handlers everywhere is possible (#4477)
v12.1.0 on 12/22/2024
2c972 - feat: add writeMode options (#4392)
v12.0.0-beta.1 on 11/21/2024
0a9ed - feat!: drop Vue 2 support, optimize bundles and clean up (#4349)
v11.3.0 on 11/21/2024
e77ca - fix: hash mode missing location.search (#4340)