N
Nuxt2mo ago
Andrew G.

Default external NuxtLinks to use target="_blank"

Is there a way to configure the default 'target' attribute value based on if it is an external vs internal link? I have not found a way, but asking before I add more lines of code to do the logic myself. Thanks.
2 Replies
kapa.ai
kapa.ai2mo ago
Hi @Andrew G.. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave: ---------------------- Yes, there is a way to configure the default 'target' attribute value for external links in Nuxt, but not specifically to differentiate between external and internal links automatically. Here's what you can do: 1. For external links, Nuxt automatically applies a default rel attribute of "noopener noreferrer" as mentioned in the documentation (https://nuxt.com/docs/api/components/nuxt-link#target-and-rel-attributes). 2. You can set a default target attribute for all NuxtLinks (both internal and external) using the nuxt.config.ts file. Here's how you can do it:
export default defineNuxtConfig({
experimental: {
defaults: {
nuxtLink: {
componentName: 'NuxtLink',
externalRelAttribute: 'noopener noreferrer',
target: '_blank'
}
}
}
})
export default defineNuxtConfig({
experimental: {
defaults: {
nuxtLink: {
componentName: 'NuxtLink',
externalRelAttribute: 'noopener noreferrer',
target: '_blank'
}
}
}
})
This configuration will set the default target attribute to "_blank" for all NuxtLinks as shown in the documentation (https://nuxt.com/docs/api/components/nuxt-link#in-nuxt-config). However, this doesn't differentiate between external and internal links automatically. If you want to apply target="_blank" only to external links, you would need to handle this logic in your component or create a custom link component. For a custom solution, you could create your own link component using defineNuxtLink and implement the logic to set target="_blank" only for external links as mentioned in the documentation (https://nuxt.com/docs/api/components/nuxt-link#custom-link-component). Remember that you can always override these defaults on a per-link basis by explicitly setting the target attribute in your <NuxtLink> components. ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ----------------------
kapa.ai
kapa.ai2mo ago
<@542080532670840832> Kapa.ai is still learning and improving, please let me know how I did by reacting below.
Want results from more Discord servers?
Add your server