[Vuejs]-How can I make dynamic parameter on the url?

2πŸ‘

For query string parameter, you can use encodeURIComponent to encode the string correctly.
Use Array.map to loop over the keys and combine final result by Array.join like this

 let params = Object.keys(payload).map(el => `${el}=${encodeURIComponent(payload[el])}`).join('&')

If your payload is {countryId: "1", clubId: "2", playerName: "ronal do "} the params become "countryId=1&clubId=2&playerName=ronal%20do%20" and it is passed to request correctly

πŸ‘€Linh Nguyen

0πŸ‘

If you so wish, you can use the npm module query-string. Link: https://www.npmjs.com/package/query-string.

You can then convert a JSON object directly into well formed search params. It provides functionality to encode as well.

πŸ‘€Gautam

-1πŸ‘

function formatQuery(payload) {
  var params = '';

  if (payload.countryId && payload.countryId.trim().length) params += `countryId=${encodeURIComponent(payload.countryId.trim())}&`;

  if (payload.clubId && payload.clubId.trim().length) params += `clubId=${encodeURIComponent(payload.clubId.trim())}&`;

  if (payload.playerName && payload.playerName.trim().length) params += `playerName=${encodeURIComponent(payload.playerName.trim())}`;


  console.log(params);
  return params;

}

formatQuery({countryId: "1", clubId: "2", playerName: "ronaldo"});

formatQuery({countryId: "1", clubId: "2"});

formatQuery({playerName: "ronaldo"});
πŸ‘€chans

Leave a comment