useQueryParam

useQueryParam binds a Vue ref (raw) or a property on a Vue ref (object) to a query parameter in the browser's url. When the ref changes, the query param will change, and when the parameter changes, the ref's value will update. useQueryParam requires VueUse's useUrlSearchParams, so your application must include VueUse as a dependency.

Important: Note that each of the examples below are competing for control of the browser's query string. Typically, the last example will be active on page load. You should select a value from the example you are exploring to ensure its query params are active.

Similarly, when using useQueryParam in your applications, it is best to specify query parameters at the page level. You cannot register params in multiple child components and expect them to combine neatly.

Behavior

  1. An existing query parameter will take precedence over a stored value on page load. For example consider we have a filter org that is stored in the page session and the query string. If the query param is 17 and the stored (ref) value is 12, the stored value will be initialized to 17.

  2. If no query param exists and the ref has a value, the value will be set in the query string. Using our previous example, say the page session had the value of 17 and there was no org query parameter. In this case, the query param would be set to the value of the ref.

  3. A watcher will be set on the ref such that all changes to the ref will be mirrored in the query string.

  4. Currently, useQueryParam does not create any routing events, so you can not use the back button to navigate changes to a parameter value.

Examples

Raw value

The simplest use of useQueryParam is to bind a query parameter directly to a ref that holds a raw value (string or number).

Object value

The second style of usage is to bind a query parameter to a property on a reactive object (e.g. a ref whose value is an object). This allows you to group parameters and pass them as a whole to things like filter components. In this case, you may want to instead use useQueryParams, which will bind all properties on an object as query parameters.

Default value

useQueryParam has an optional fourth parameter, defaultValue, that allows you to define the default value for the param. When the ref equals the default value, the query parameter will not be included in the url. This helps keep the url as concise as possible. Set Key to 11 below and notice that the query param disappears.

Multiple parameters

useQueryParam will automatically collect multiple values for the same query parameter into and array. However, if only one value is present, VueUse's useUrlSearchParams will provide a single value and not an array with a single value. You can ensure an array is returned in this case by specifying useQueryParam with a default value that is an array.

PENDING, ACTIVE
[ "PENDING", "ACTIVE" ]

Reference