@smart-gate/query-params
v1.0.0
Published
A JavaScript package for synchronizing reactive objects with URL query parameters.
Downloads
75
Readme
@smart-gate/query-params
A composable function for synchronizing data with URL query parameters. This package allows you to keep your application's state in sync with the URL, making it easier to share and manage state across different views and sessions.
Features
- Synchronize Data objects with URL query parameters.
- Custom serialization and deserialization.
- Configurable URL update behavior.
- Works with all freamworks
Installation
You can install the package via npm:
npm install @smart-gate/query-params
or with yarn:
yarn add @smart-gate/query-params
Usage
Example Component
Here's a simple example of a Vue component using @smart-gate/query-params:
<template>
<div class="w-screen font-mono h-screen flex items-center mx-auto justify-center">
{{ filter }}
<div class="flex flex-col gap-5">
<input v-model="filter.name" placeholder="Name" />
<input v-model="filter.age" placeholder="Age" type="number" />
<input v-model="filter.gender" placeholder="Gender" />
</div>
</div>
</template>
<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { useQueryParams } from '@smart-gate/query-params';
interface IFilter {
name?: string;
age?: number;
gender?: string;
}
const filter = ref<IFilter>({});
const { initializeDataFromQuery, updateQueryParams } = useQueryParams(filter.value);
onMounted(() => {
initializeDataFromQuery();
});
onUpdated(() => {
updateQueryParams();
});
</script>
API
useQueryParams<T>
Parameters
data: T
: An object containing the data to sync with the URL.options
(optional): Configuration options.serialize?: (key: keyof T, value: unknown) => string
: Custom serialization function.deserialize?: (key: keyof T, value: string) => unknown
: Custom deserialization function.updateUrl?: boolean
: Whether to automatically update the URL when the data changes.
Returns
initializeDataFromQuery
: Function to initialize data from the URL query parameters.updateQueryParams
: Function to manually trigger the update of query parameters.
Configuration
You can customize the serialization and deserialization functions by providing options:
const { initializeDataFromQuery } = useQueryParams(
filter,
{
serialize: (key, value) => JSON.stringify(value),
deserialize: (key, value) => JSON.parse(value),
updateUrl: true
}
);