@zphhpzzph/use-url-search-param
v1.0.0
Published
Vue 3 hooks for synchronizing URL search parameters with reactive state
Maintainers
Readme
@crm/use-url-search-param
Vue 3 hooks for synchronizing URL search parameters with reactive state.
Features
- 🔄 Sync URL search parameters with reactive state automatically
- 📦 Batch updates for better performance
- 🎯 TypeScript support with full type safety
- 🔧 Flexible options for custom parsing and formatting
- ⚡ Built on Vue 3 Composition API and Vue Router
Installation
pnpm add @crm/use-url-search-paramUsage
useURLSearchParam
Sync a single URL search parameter with a ref:
import { useURLSearchParam } from '@crm/use-url-search-param';
// The hook will sync the 'page' URL parameter with the returned ref
const page = useURLSearchParam('page', '1');
// When page.value changes, the URL will be updated automatically
page.value = '2'; // URL becomes ?page=2useURLSearchParams
Sync multiple URL search parameters with a reactive object:
import { useURLSearchParams } from '@crm/use-url-search-param';
// Sync multiple parameters
const filters = useURLSearchParams({
page: 1,
pageSize: 10,
search: '',
});
// When filters.value changes, all URL parameters are updated
filters.value = {
page: 2,
pageSize: 20,
search: 'keyword',
};
// URL becomes ?page=2&pageSize=20&search=keyworduseURLSearch
Watch a reactive value and sync it to URL:
import { useURLSearch } from '@crm/use-url-search-param';
const someRef = ref('value');
// Watch someRef and sync to URL parameter 'key'
useURLSearch('key', () => someRef.value, (val) => val);API Reference
useURLSearchParam(paramName, defaultValue)
Sync a single URL parameter.
- paramName:
string- The URL parameter name - defaultValue:
LocationQueryValue | undefined- Default value if not in URL - Returns:
Ref<LocationQueryValue | undefined>- Reactive ref synchronized with URL
useURLSearchParams(object, options?)
Sync multiple URL parameters.
- object:
T- Default values for parameters - options:
Options(optional)- readFromURLQuery: Function to parse URL values to desired type
- setURLQuery: Function to format values for URL
- Returns:
Ref<T>- Reactive ref synchronized with URL
useURLSearch(key, reactiveFn, parse)
Watch a reactive value and sync to URL.
- key:
string- The URL parameter name - reactiveFn:
() => T | undefined- Function that returns the value to watch - parse:
(val: T) => LocationQueryValue | LocationQueryValue[]- Function to format value for URL
Peer Dependencies
vue: ^3.0.0vue-router: ^4.0.0
License
MIT
