Currently, I have been saving a parameter to the URL in the following manner:
const save = async (parameter: LocationQuery) => {
await router.push({ path: '', query: { ...route.query, ...parameter } });
};
This is how I call it:
save({ param1: 'abc' });
When it comes to reading and monitoring parameters, I do it like this:
const route = useRoute();
const x = route.query.param1;
const y = computed(() => route.query.param1);
But managing multiple query parameters scattered across different parts of the code isn't ideal. I want to standardize their usage so that I don't have hardcoded names everywhere.
One solution could be creating an enum with the parameter names:
export enum QueryParams {
Param1 = 'param1',
Param2 = 'param2'
// ...
}
I can then utilize it for accessing and monitoring the parameters:
const route = useRoute();
const x = route.query[QueryParams.Param1 as string];
const y = computed(() => route.query[QueryParams.Param1 as string]);
The challenge arises when trying to use the enum value in the save function. For instance:
const save = async (name: QueryParams, value: string | number | undefined) => {
const parameter = // How can I construct this parameter?
await router.push({ path: '', query: { ...route.query, ...parameter } });
};
The straightforward approach doesn't work:
const parameter = { name: value }; // This would create 'name=' parameter instead of 'param1='
Is there a way to utilize an enum value in constructing a LocationQuery
parameter? If not, what would be a better alternative to avoid hardcoding query parameter names?
Thank you in advance.