In Nuxt 3 (3.10.3) I am trying to dynamically load Google fonts based on a query parameter in the URL.
Load font in onBeforeMount
based on that route query parameter:
onBeforeMount(() => {
link: [
{
rel: 'preconnect',
href: 'https://fonts.googleapis.com'
},
{
rel: 'preconnect',
href: 'https://fonts.gstatic.com',
crossorigin: '',
},
{
rel: 'stylesheet',
href: `https://fonts.googleapis.com/css2?family=${route.query.font}:ital,wght@0,100;0,300;0,400;0,500;0,700;0,900;1,100;1,300;1,400;1,500;1,700;1,900&display=swap`
}
]
})
Set the font-family in <template>
:
<ClientOnly>
<component is="style">
html {
font-family: {{ font }}, 'Open Sans', sans-serif !important;
}
</component>
</ClientOnly>
This works fine, but I would expect this to work as well with useHead()
.
It works well when I add the styling (add font-family rule) via a custom <style>
tag, but does not if I use the useHead()
Nuxt composable to set the htmlAttrs.style
there. What difference is there in these two approaches? There’s just no where I can put the useHead composable (onload of the font script, onMounted
, anywhere in script setup) to make this work without having the CSS in template.
Tomáš is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.