nuxt: Can't use is="NuxtLink" with component

Environment


  • Operating System: Darwin
  • Node Version: v14.18.2
  • Nuxt Version: 3.0.0-27468803.23e7afb
  • Package Manager: yarn@1.22.17
  • Builder: vite
  • User Config: css, build
  • Runtime Modules: -
  • Build Modules: -

Reproduction

<component is="NuxtLink" to="/">Example</component>

Generate this html:

<nuxtlink to="/">Example</nuxtlink>

Expected html:

<a aria-current="page" href="/" class="router-link-active router-link-exact-active">Example</a>

Describe the bug

Usage of <component is="NuxtLink" to="/"> doesn’t generate a link, I can’t use <component :is="to ? 'NuxtLink' : href ? 'a' : 'button'"

Additional context

No response

Logs

No response

About this issue

  • Original URL
  • State: closed
  • Created 2 years ago
  • Reactions: 1
  • Comments: 15 (7 by maintainers)

Most upvoted comments

Or, to reuse the existing NuxtLink component:

const component = computed(() => {
  if (props.to || props.href) return resolveComponent('NuxtLink')
  return 'button'
})

Example: https://stackblitz.com/edit/github-vwzpk9?file=app.vue.

The reason this is required is that if you don’t use NuxtLink it won’t be included in your bundle. So we need more than just a string to tell us.

If you want it globally registered then you can create your own NuxtLink component with defineNuxtLink in your components directory and set components.global to true in your nuxt.config. See https://github.com/nuxt/framework/pull/3305 for some context.

First you can use nuxt-link for external links now. Check the doc: https://v3.nuxtjs.org/docs/usage/nuxt-link.

If you still need to use it in is prop, you can use defineNuxtLink({}) instead of nuxt-link:

const component = computed(() => {
  if (props.to || props.href) return defineNuxtLink({})
  return 'button'
})

For those wondering, the correct import is import { NuxtLink } from '#components'; Then you can use: <component :is="to ? NuxtLink : 'div'" :to="to">, Nuxt need better documentation about the Virtual Files, they are helpful, but confusing.

Sometimes life is like a joke, I’ve created a reproduction repo and… it works just fine 😃 Tried again in the project, and it works too… So, thanks again 👍

@deflexor it will work if you use a script setup block, where the import is automatically exposed. Otherwise you need to pass it explicitly to the template.

@Dodje It’s because NuxtLink isn’t globally registered - it’s auto-imported. Within a Nuxt project we detect resolveComponent('NuxtLink') and rewrite this into an import statement.

You can probably resolve this in your case by adding your ui library to build.transpile, and using import { NuxtLink } from '#imports'