Skip to content

data-query-string

Declare a signal that is kept in sync with a URL query parameter, both ways: the parameter seeds the signal on load, changes to the signal rewrite the address, and the parameter disappears when the value is back at its default.

data-query-string:page="1" <!-- ?page= ↔ $page, default 1 -->
data-query-string:sort-by="'name'" <!-- ?sort-by= ↔ $sortBy -->
data-query-string:q__history="''" <!-- pushes a history entry per change -->
part
key required: the parameter name as written; the signal is the camelCased key
value optional: the default, as an expression ('' when omitted)
modifier effect
__history pushState an entry per change and restore the signal on Back and Forward
__case.kebab keep the signal name kebab-cased
default is dropped from the URL

tab = ; watch the address bar:

<div data-query-string:tab="'one'">
<div class="row"><button data-on:click="$tab = 'one'">one</button><button data-on:click="$tab = 'two'">two</button><button data-on:click="$tab = 'three'">three</button></div>
<p>tab = <b data-text="$tab"></b>; watch the address bar: <code data-text="location.search || '(no query)'" data-on-signal-patch="el.textContent = location.search || '(no query)'"></code></p>
</div>

The parameter takes the default’s type. With a number, boolean, array or object default the parameter is parsed as JSON, so ?page=2 gives the number 2 and ?tags=["a"] an array; with a string default it stays text, so ?code=007 keeps its leading zeros.

numbers stay numbers
()
<div data-query-string:page="1">
<div class="row"><button data-on:click="$page--">previous</button> <b data-text="$page"></b> (<span data-text="typeof $page"></span>) <button data-on:click="$page++">next</button></div>
</div>

With __history every change pushes an entry, so Back walks through previous filters and the signal follows.

__history

q =

<div data-query-string:q__history="''">
<input data-bind:q__event.change placeholder="type, press Enter, then use Back">
<p>q = <b data-text="$q"></b></p>
</div>

Objects are stored as JSON in the parameter. When the parameter is present on load it wins over an existing signal value; when absent, the default applies. Without __history the address is replaced, leaving one history entry. To reflect a whole computed path rather than one parameter, see data-replace-url.

import { queryString } from 'sigmx/plugins'

Registering queryString adds 429 bytes brotli (465 gzip, 955 minified) on top of the core. See bundle sizes.