N
Nuxtβ€’9mo ago
Cry0nicS

Pass URL query params to href

I have a button with a link that looks like this
<Button
:href="$t('cta.button.url')"
size="xl"
variant="primary">
{{ $t("cta.button") }}
</Button>
<Button
:href="$t('cta.button.url')"
size="xl"
variant="primary">
{{ $t("cta.button") }}
</Button>
I want to read all the query params from this page and pass them along to this href. I tried something like
<script lang="ts">
const {t} = useI18n();
const route = useRoute();
const query = route.query;

const buttonUrl = computed(() => {
// Get the base URL from translations
const baseUrl = t('cta.button.url');
// Convert the route query parameters to a query string
const queryString = new URLSearchParams(query).toString();

// Return the full URL, appending the query string if it exists
return queryString ? `${baseUrl}?${queryString}` : baseUrl;
});
</script>
<script lang="ts">
const {t} = useI18n();
const route = useRoute();
const query = route.query;

const buttonUrl = computed(() => {
// Get the base URL from translations
const baseUrl = t('cta.button.url');
// Convert the route query parameters to a query string
const queryString = new URLSearchParams(query).toString();

// Return the full URL, appending the query string if it exists
return queryString ? `${baseUrl}?${queryString}` : baseUrl;
});
</script>
However, the URLSearchParams doesn't take a LocationQuery (that is being return from route.query). What's the best way to sort this out?
5 Replies
manniL
manniLβ€’9mo ago
you could use ufo's utils instead of URLSearchParams.toString()
manniL
manniLβ€’9mo ago
GitHub
GitHub - unjs/ufo: πŸ”— URL utils for humans
πŸ”— URL utils for humans. Contribute to unjs/ufo development by creating an account on GitHub.
Cry0nicS
Cry0nicSOPβ€’9mo ago
Thanks. If I can, however, I'd like to avoid using another library just for this use case Actually, seems like I don't need to install it.
// Stringfy and encode the query object into a query string.
const queryString = stringifyQuery(query);

// Return the full URL, appending the query string if it exists
return queryString ? `${baseUrl}?${queryString}` : baseUrl;
// Stringfy and encode the query object into a query string.
const queryString = stringifyQuery(query);

// Return the full URL, appending the query string if it exists
return queryString ? `${baseUrl}?${queryString}` : baseUrl;
This seemed to have worked.
manniL
manniLβ€’9mo ago
that's already part of nuxt πŸ˜‰
Cry0nicS
Cry0nicSOPβ€’9mo ago
Pretty cool, didn't know. Thanks
Want results from more Discord servers?
Add your server