How to syncronize Alpine.js data with URL query parameters
To synchronize Alpine.js data with the query parameters in the URL, all you need to do is $watch the property and write its value to the URL. On page load you need to read the value of the property from the URL and initialize Alpine.js data with this value.
Its possible to extend Alpine.js to implement a generic version of above approach: “Alpine.js allows you to register your own custom directives using the Alpine.directive() API.”
const updateQueryParam = (paramName, newValue) => {
const url = new URL(window.location)
url.searchParams.set(paramName, newValue);
window.history.replaceState({}, '', url);
};
document.addEventListener('alpine:init', () => {
Alpine.directive('query-string', (el, { _modifiers, expression }, { evaluate }) => {
const urlParams = new URLSearchParams(window.location.search)
const paramName = expression;
const initialValue = urlParams.get(paramName) ?? evaluate(expression);
Alpine.bind(el, {
'x-data'() {
return {
init() {
this[paramName] = initialValue
this.$watch(expression, (value) => {
updateQueryParam(paramName, value)
})
},
}
},
})
})
})
Use above defined directive in HTML like this:
<input type="text" id="name" name="name" x-model="name" x-query-string="name">
See this demo page for a working example. The code is on GitHub.