Last active
June 22, 2021 11:51
-
-
Save AllanJeremy/4918e37f464fbb3b3f3096678b223375 to your computer and use it in GitHub Desktop.
VueJS - Get a link with query params from the current url preserved
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** Get a link with query params from the current url preserved | |
* @param {String} redirectLink The link to append params to | |
* @param {Object} $route The VueJS route object. Should contain a `query` object | |
* @return {String} The redirect link with url params from the current page appended | |
*/ | |
const getLinkWithQueryParams = (redirectLink, $route) => { | |
const { query } = $route | |
// Return the link as is if no query params were found | |
if (!Object.keys(query).length) { | |
return redirectLink | |
} | |
const queryKeys = Object.keys(query) | |
queryKeys.forEach((param, i) => { | |
const paramValue = query[param] | |
// Only add `?` if there are no existing query params in the redirect url provided | |
if (i === 0 && !redirectLink.includes('?')) { | |
redirectLink += '?' | |
} else { | |
// First and last params don't have a `&` prepended to them | |
redirectLink += '&' | |
} | |
redirectLink += `${param}=${paramValue}` | |
}) | |
return redirectLink | |
} | |
//* EXPORTS | |
export { getLinkWithQueryParams } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment