Tips for dynamically generating parameter names for query usage with vue-router

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.

Answer №1

One way to dynamically change a query parameter (name) is by using computed property syntax:

router.push({ path: '', query: { ...route.query, [name]: value } })

If multiple parameters are constantly changing and affecting the application state, it might suggest a design issue. Usually, global states do not need to be passed through URLs; they can be stored in a centralized store or browser storage for persistence.

If the goal is to provide state through a link without relying on a specific client's browser, this can still be accomplished using global state. Instead of manually setting query parameters, the state can serve as the single source of truth, like myState.param1 = 'abc'. This state can then be automatically synchronized with the route URL. The purpose of router.push may involve more than just updating query parameters, so they can be managed within a watcher for myState, or in router hooks like beforeEach/beforeEnter depending on the requirements.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encountering a white screen and MIME Type Error when attempting to deploy a Vite app on GitLab Pages

I am facing an issue while trying to deploy my Vite application on Gitlab Pages. The page only displays a blank screen and the following errors are shown: The CSS and JS files from the static directory cannot be loaded due to MIME type mismatch (X-Content ...

Dealing with errors in Next.js 13 with middleware: a comprehensive guide

My attempt to manage exceptions in Next.js 13 using middleware is not producing the desired results. Below is my current code: import { NextRequest, NextFetchEvent, NextResponse } from "next/server" export function middleware(req: NextRequest, e ...

Error: The property 'inputItem' is not recognized on type 'EventTarget' - Utilizing Semantic-Ui, React, and Typescript

Currently, I'm utilizing React, Typescript, and Semantic UI react components. My aim is to clear the input field after successfully adding an item. While debugging, I've noticed the event.currentTarget.inputName.value which I wish to set to an em ...

Changing the format of a numerical value to include commas for every 1000 increment

I'm trying to find a way to format numbers in a specific manner, such as changing 1234567 into 1,234,567. However, I've run into some issues when attempting to use the currency pipe of TypeScript. It adds USD or $ in front of the number, which i ...

Is there a way to selectively disable the beforeRouteLeave in Vue.js for certain scenarios, or alternatively, activate it only under specific conditions?

Utilizing beforeRouteLeave to display a warning during screen transitions, however, it triggers in all cases within that specific URL. I am specifically interested in making it function only when importing a file within that URL (while the progress bar is ...

An error occurs in TypeScript when attempting to reduce a loop on an array

My array consists of objects structured like this type AnyType = { name: 'A' | 'B' | 'C'; isAny:boolean; }; const myArray :AnyType[] =[ {name:'A',isAny:true}, {name:'B',isAny:false}, ] I am trying ...

Record the user actions from logging in through Facebook or OAuth and store them in the database

I have been attempting to log in with Facebook using Firebase. How can I save user information such as email and username to the database? Additionally, I am unsure of what steps to take next when users engage in activities like ordering products on my w ...

Tips for utilizing JavaScript object destructuring to extract a specific portion of an argument while still keeping a reference to the rest of the properties in a single value

In my current project, I am exploring the possibility of using TypeScript/Javascript object destructuring to target only certain properties of an object while preserving the rest of the properties in a separate variable. I am specifically looking for a way ...

Implementing dynamic classes for each level of ul li using JavaScript

Can anyone help me achieve the goal of assigning different classes to each ul li element in vanilla Javascript? I have attempted a solution using jQuery, but I need it done without using any libraries. Any assistance would be greatly appreciated! con ...

Is it possible to combine TypeScript modules into a single JavaScript file?

Hey there, I'm feeling completely lost with this. I've just started diving into Typescript with Grunt JS and I could really use some assistance. I already have a Grunt file set up that runs my TS files through an uglify process for preparing the ...

Step-by-step guide on mocking a method within a method using JEST

Currently, I am facing a challenge in unit testing a method named search. This method consists of three additional methods - buildSearchParameter, isUnknownFields, and readAll. I am looking to mock these methods but I am uncertain about the process. Can ...

Switching between different types of generic functions in typescript

Is there a way to convert between these two types of generic functions: type Foo=<S>(a: S) => S type FooReturnType = ReturnType<Foo> // unknown type Bar<S> = { (a: S): S } type BarReturnType = ReturnType<Bar<string> ...

Attempting to incorporate Vue.js into the Vue router

Is it possible to include the 'import {vue} from 'vue' statement in the Vue router file? import home from '../components/home.vue' import {vue} from 'vue' import VueMeta from 'vue-meta' // Code for vue-meta us ...

Using 'import' and 'export' in Ionic 2 requires specifying 'sourceType: module'

Starting a new project using Ionic 2 and encountering an error after installing angular2-jwt: ParseError: 'import' and 'export' may appear only with 'sourceType: module' D:\desenv\arquivos\workspace_inbit&bsol ...

Tips on excluding node_modules from typescript in Next.js 13

I am constructing a website in the next 13 versions with TypeScript, using the src folder and app directory. When I execute `npm run dev`, everything functions correctly. However, upon building, I encounter this error... ./node_modules/next-auth/src/core/l ...

What steps can be taken to patch a type during the compilation process?

Is it possible to achieve the necessary dynamic typing in TypeScript to establish a component system of this nature? let block = new Entity(); // block.components === {}; block.has(new Position(0, 0)); // block.components === { position: { ... } } In thi ...

There was a TypeError error that occurred: Unable to access the property 'title' of null in Angular/Firebase

Seeking to retrieve data from Firebase's real-time database by passing values in an input form, I encountered an issue whenever I attempt to utilize [(ngModel)]="product.title". ERROR TypeError: Cannot read property 'title' of nu ...

The Quasar application is facing difficulty in establishing a connection with the socket.io server on her

I've been attempting to establish a connection between my Quasar application and a socket.io express server hosted on Heroku. However, every time I try to connect, the browser displays the request is pending, and on the backend, I never receive the co ...

Create a function that takes in a function as an argument and generates a new function that is identical to the original function, except it has one

I want to establish a function called outerFn that takes another function (referred to as innerFn) as a parameter. The innerFn function should expect an object argument with a mandatory user parameter. The main purpose of outerFn is to return a new functio ...

What is the proper way to set up redirects in Spring Security when integrating with a Vue.js frontend and OAuth2.0?

We currently have a scenario in which a user is sent a link via email. For instance, the link provided is as follows: http://localhost:8080/#approveData?uploadId=134 Everything works smoothly if the user has already signed in using our OAuth2-based SSO. ...