Vue useUrlSearchParams 获取和设置url参数

Vue useUrlSearchParams 获取和设置url参数,这是一个非常有用的函数,我们在实际开发中经常或需要获取url参数的值,当然我们可以通过vue的路由和页面的属性获取,但是无法进行修改该参数,而useUrlSearchParams则是响应式的可以进行修改。

代码示例

iimport { useUrlSearchParams } from '@vueuse/core'

const params = useUrlSearchParams('history')

console.log(params)  

params.id= '100';
params.name= 'itxst.com'
// url参数更新为 100和itxst.com

hash模式

import { useUrlSearchParams } from '@vueuse/core'

const params = useUrlSearchParams('hash')

params.id= '100';
params.name= 'itxst.com'
// url updated to `#/your/route?id=100&itxst.com`

Hash Params

import { useUrlSearchParams } from '@vueuse/core'


const params = useUrlSearchParams('hash-params')

params.id= '100';
params.name= 'itxst.com'
// url updated to `/your/route#id=100&name=itxst.com`

在线例子

在线试一试

类型定义

export type UrlParams = Record<string, string[] | string>
export interface UseUrlSearchParamsOptions<T> extends ConfigurableWindow {
  /**
   * @default true
   */
  removeNullishValues?: boolean
  /**
   * @default false
   */
  removeFalsyValues?: boolean
  /**
   * @default {}
   */
  initialValue?: T
  /**
   * Write back to `window.history` automatically
   *
   * @default true
   */
  write?: boolean
}
/**
 * Reactive 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