A tiny Vue composable function to create a ref synced with vue router query.
Works for Vue 2 and Vue 3 within a single package by the power of vue-demi!
npm install --save vue-use-route-query
or
yarn add vue-use-route-query
or
pnpm install vue-use-route-query
Simple example with a string parameter without any transformations
import { defineComponent } from 'vue'
import { useRouteQuery } from 'vue-use-route-query'
export default defineComponent({
setup() {
const foo = useRouteQuery('foo', ''); // Ref<string>
const bar = useRouteQuery('bar', null); // Ref<string | null>
foo.value = 'foo'; // Results in 'foo=foo' in the query
return {
foo,
bar,
}
}
})
More complex example with a transformer
import { defineComponent } from 'vue'
import { useRouteQuery, RouteQueryTransformer } from 'vue-use-route-query'
export default defineComponent({
setup() {
// This transformer will reverse the string because why not
const reverseTransformer: RouteQueryTransformer<string> = {
fromQuery(query) {
return query.split('').reverse().join('');
},
toQuery(value) {
return value?.split('').reverse().join('');
}
}
const foo = useRouteQuery('foo', '', reverseTransformer);
foo.value = 'bar'; // Results in 'foo=rab' in the query
return {
foo,
}
}
})
A several transformers provided by the library out of the box:
integerTransformer
const foo = useRouteQuery('foo', 0, integerTransformer); // Ref<number>
floatTransformer
const foo = useRouteQuery('foo', 0, floatTransformer); // Ref<number>
booleanTransformer
const foo = useRouteQuery('foo', false, booleanTransformer); // Ref<boolean>
enumTransformer
- stores the enum key in the query and maps it back to the enum valueenum Foo { BAR, BAZ } const foo = useRouteQuery('foo', Foo.Bar, enumTransformer); // Ref<Foo> foo.value = Foo.BAZ; // Results in 'foo=BAZ' in the query