<NuxtLink>

Nuxt는 애플리케이션 내의 모든 종류의 링크를 처리하기 위해 <NuxtLink> 컴포넌트를 제공합니다.
<NuxtLink>는 Vue Router의 <RouterLink> 컴포넌트와 HTML의 <a> 태그를 대체할 수 있는 드롭인 컴포넌트입니다. 이 컴포넌트는 링크가 내부 링크인지 외부 링크인지 지능적으로 판단하여, 사용 가능한 최적화(프리페치, 기본 속성 등)와 함께 적절하게 렌더링합니다.

내부 라우팅

이 예제에서는 <NuxtLink> 컴포넌트를 사용하여 애플리케이션의 다른 페이지로 링크를 연결합니다.

<template>
  <NuxtLink to="/about">About page</NuxtLink>
</template>

동적 라우트에 파라미터 전달하기

이 예제에서는 id 파라미터를 전달하여 ~/pages/posts/[id].vue 라우트로 링크를 연결합니다.

<template>
  <NuxtLink :to="{ name: 'posts-id', params: { id: 123 } }">
    Post 123
  </NuxtLink>
</template>
Nuxt DevTools의 Pages 패널에서 라우트 이름과 해당 라우트가 받을 수 있는 파라미터를 확인할 수 있습니다.

정적 파일 및 크로스 앱 링크 처리

기본적으로 <NuxtLink>는 상대 경로에 대해 Vue Router의 클라이언트 사이드 내비게이션을 사용합니다. /public 디렉토리의 정적 파일이나 동일 도메인에 호스팅된 다른 애플리케이션으로 링크를 연결할 때, 이들은 클라이언트 라우트에 포함되어 있지 않기 때문에 예기치 않은 404 오류가 발생할 수 있습니다. 이런 경우, <NuxtLink>external prop을 사용하여 Vue Router의 내부 라우팅 메커니즘을 우회할 수 있습니다.

external prop은 해당 링크가 외부 링크임을 명시적으로 나타냅니다. <NuxtLink>는 이 링크를 표준 HTML <a> 태그로 렌더링합니다. 이를 통해 Vue Router의 로직을 우회하고 리소스에 직접 연결되어 링크가 올바르게 동작하도록 보장합니다.

정적 파일로 링크 연결하기

PDF나 이미지와 같은 /public 디렉토리의 정적 파일에 대해, external prop을 사용하여 링크가 올바르게 연결되도록 할 수 있습니다.

pages/index.vue
<template>
  <NuxtLink to="/example-report.pdf" external>
    Download Report
  </NuxtLink>
</template>

크로스 앱 URL로 링크 연결하기

동일 도메인 내의 다른 애플리케이션을 가리킬 때, external prop을 사용하면 올바른 동작을 보장할 수 있습니다.

pages/index.vue
<template>
  <NuxtLink to="/another-app" external>
    Go to Another App
  </NuxtLink>
</template>

external prop을 사용하거나 자동 처리를 활용하면 올바른 내비게이션이 보장되고, 예기치 않은 라우팅 문제를 방지하며, 정적 리소스나 크로스 애플리케이션 시나리오와의 호환성이 향상됩니다.

외부 라우팅

이 예제에서는 <NuxtLink> 컴포넌트를 사용하여 웹사이트로 링크를 연결합니다.

app.vue
<template>
  <NuxtLink to="https://nuxtjs.org">
    Nuxt website
  </NuxtLink>
  <!-- <a href="https://nuxtjs.org" rel="noopener noreferrer">...</a> -->
</template>

relnoRel 속성

target 속성이 있거나 절대 링크(예: http://, https://, //로 시작하는 링크)에 대해 기본적으로 noopener noreferrerrel 속성이 적용됩니다.

  • noopener는 구형 브라우저의 보안 버그를 해결합니다.
  • noreferrer는 연결된 사이트에 Referer 헤더를 보내지 않아 사용자의 프라이버시를 향상시킵니다.

이러한 기본값은 SEO에 부정적인 영향을 주지 않으며, 권장되는 모범 사례로 간주됩니다.

이 동작을 덮어써야 할 경우 rel 또는 noRel props를 사용할 수 있습니다.

app.vue
<template>
  <NuxtLink to="https://twitter.com/nuxt_js">
    Nuxt Twitter
  </NuxtLink>
  <!-- <a href="https://twitter.com/nuxt_js" rel="noopener noreferrer">...</a> -->

  <NuxtLink to="https://discord.nuxtjs.org" rel="noopener">
    Nuxt Discord
  </NuxtLink>
  <!-- <a href="https://discord.nuxtjs.org" rel="noopener">...</a> -->

  <NuxtLink to="/about" target="_blank">About page</NuxtLink>
  <!-- <a href="/about" target="_blank" rel="noopener noreferrer">...</a> -->
</template>

noRel prop을 사용하면 절대 링크에 기본 rel 속성이 추가되지 않도록 할 수 있습니다.

app.vue
<template>
  <NuxtLink to="https://github.com/nuxt" no-rel>
    Nuxt GitHub
  </NuxtLink>
  <!-- <a href="https://github.com/nuxt">...</a> -->
</template>
noRelrel은 함께 사용할 수 없습니다. rel은 무시됩니다.

프리페치 링크

Nuxt는 자동으로 스마트 프리페치 기능을 포함합니다. 즉, 링크가 (기본적으로) 뷰포트에 보이거나 스크롤될 때 이를 감지하여 해당 페이지의 JavaScript를 미리 가져와 사용자가 링크를 클릭할 때 바로 준비되도록 합니다. Nuxt는 브라우저가 바쁘지 않을 때만 리소스를 로드하며, 오프라인이거나 2g 연결만 있을 경우 프리페치를 건너뜁니다.

pages/index.vue
<NuxtLink to="/about" no-prefetch>About page not pre-fetched</NuxtLink>
<NuxtLink to="/about" :prefetch="false">About page not pre-fetched</NuxtLink>

커스텀 프리페치 트리거

v3.13.0 이후 <NuxtLink>에 대해 커스텀 프리페치 트리거를 지원합니다. prefetchOn prop을 사용하여 링크 프리페치 시점을 제어할 수 있습니다.

<template>
  <NuxtLink prefetch-on="visibility">
    This will prefetch when it becomes visible (default)
  </NuxtLink>

  <NuxtLink prefetch-on="interaction">
    This will prefetch when hovered or when it gains focus
  </NuxtLink>
</template>
  • visibility: 링크가 뷰포트에 보이게 될 때 프리페치합니다. Intersection Observer API를 사용하여 요소가 뷰포트와 교차하는지 모니터링합니다. 요소가 뷰에 들어오면 프리페치가 트리거됩니다.
  • interaction: 링크에 마우스를 올리거나 포커스될 때 프리페치합니다. 이 방식은 pointerenterfocus 이벤트를 감지하여 사용자가 상호작용 의도를 보일 때 리소스를 미리 가져옵니다.

객체를 사용하여 prefetchOn을 구성할 수도 있습니다:

<template>
  <NuxtLink :prefetch-on="{ interaction: true }">
    This will prefetch when hovered or when it gains focus
  </NuxtLink>
</template>

둘 다 활성화하고 싶지 않을 수도 있습니다!

<template>
  <NuxtLink :prefetch-on="{ visibility: true, interaction: true }">
    This will prefetch when hovered/focus - or when it becomes visible
  </NuxtLink>
</template>

이 구성은 요소가 뷰포트에 들어올 때와 pointerenter, focus 이벤트를 모두 감지합니다. 두 트리거가 서로 다른 조건에서 동일한 리소스를 프리페치할 수 있으므로 불필요한 리소스 사용이나 중복 프리페치가 발생할 수 있습니다.

크로스 오리진 프리페치 활성화

크로스 오리진 프리페치를 활성화하려면 nuxt.config에서 crossOriginPrefetch 옵션을 설정할 수 있습니다. 이 옵션은 Speculation Rules API를 사용하여 크로스 오리진 프리페치를 활성화합니다.

nuxt.config.ts
export default defineNuxtConfig({
  experimental: {
    crossOriginPrefetch: true,
  },
})

글로벌 프리페치 비활성화

앱의 모든 링크에 대해 프리페치를 전역적으로 활성화/비활성화할 수도 있습니다.

nuxt.config.ts
export default defineNuxtConfig({
  experimental: {
    defaults: {
      nuxtLink: {
        prefetch: false,
      },
    },
  },
})

Props

external을 사용하지 않을 때, <NuxtLink>는 Vue Router의 모든 RouterLink props를 지원합니다.

  • to: 모든 URL 또는 Vue Router의 route location object
  • custom: <NuxtLink>가 자신의 콘텐츠를 <a> 요소로 감쌀지 여부. 링크가 렌더링되는 방식과 클릭 시 내비게이션 동작을 완전히 제어할 수 있습니다. Vue Router의 custom prop과 동일하게 동작합니다.
  • exactActiveClass: 정확히 활성화된 링크에 적용할 클래스. 내부 링크에서 Vue Router의 exactActiveClass prop과 동일하게 동작합니다. 기본값은 Vue Router의 기본값("router-link-exact-active")입니다.
  • activeClass: 활성화된 링크에 적용할 클래스. 내부 링크에서 Vue Router의 activeClass prop과 동일하게 동작합니다. 기본값은 Vue Router의 기본값("router-link-active")입니다.
  • replace: 내부 링크에서 Vue Router의 replace prop과 동일하게 동작합니다.
  • ariaCurrentValue: 정확히 활성화된 링크에 적용할 aria-current 속성 값. 내부 링크에서 Vue Router의 ariaCurrentValue prop과 동일하게 동작합니다.
  • href: to의 별칭. to와 함께 사용하면 href는 무시됩니다.
  • noRel: true로 설정하면 외부 링크에 rel 속성이 추가되지 않습니다.
  • external: 링크를 Vue Router의 RouterLink 대신 <a> 태그로 강제로 렌더링합니다.
  • prefetch: 활성화되면 뷰포트 내의 링크에 대한 미들웨어, 레이아웃, 페이로드(payloadExtraction 사용 시)를 프리페치합니다. 실험적 crossOriginPrefetch 설정에서 사용됩니다.
  • prefetchOn: 링크 프리페치 시점을 커스텀 제어할 수 있습니다. 가능한 옵션은 interactionvisibility(기본값)입니다. 예를 들어 { interaction: true, visibility: true }와 같이 객체로도 전달할 수 있습니다. 이 prop은 prefetch가 활성화(기본값)되어 있고 noPrefetch가 설정되지 않은 경우에만 사용됩니다.
  • noPrefetch: 프리페치를 비활성화합니다.
  • prefetchedClass: 프리페치된 링크에 적용할 클래스.

Anchor

  • target: 링크에 적용할 target 속성 값
  • rel: 링크에 적용할 rel 속성 값. 외부 링크의 기본값은 "noopener noreferrer"입니다.
기본값은 덮어쓸 수 있습니다. 변경하려면 기본값 덮어쓰기를 참고하세요.

기본값 덮어쓰기

Nuxt 설정에서

nuxt.config에서 <NuxtLink>의 일부 기본값을 덮어쓸 수 있습니다.

이 옵션들은 향후 app.configapp/ 디렉토리 등 다른 위치로 이동될 수 있습니다.
nuxt.config.ts
export default defineNuxtConfig({
  experimental: {
    defaults: {
      nuxtLink: {
        // 기본값
        componentName: 'NuxtLink',
        externalRelAttribute: 'noopener noreferrer',
        activeClass: 'router-link-active',
        exactActiveClass: 'router-link-exact-active',
        prefetchedClass: undefined, // 유효한 문자열 클래스명 사용 가능
        trailingSlash: undefined // 'append' 또는 'remove' 사용 가능
        prefetch: true,
        prefetchOn: { visibility: true } 
      }
    }
  }
})

커스텀 링크 컴포넌트

defineNuxtLink을 사용하여 자신만의 링크 컴포넌트를 만들어 <NuxtLink>의 기본값을 덮어쓸 수 있습니다.

components/MyNuxtLink.ts
export default defineNuxtLink({
  componentName: 'MyNuxtLink',
  /* 아래 시그니처 참고 */
})

이제 새로운 기본값으로 <MyNuxtLink /> 컴포넌트를 평소처럼 사용할 수 있습니다.

interface NuxtLinkOptions {
  componentName?: string;
  externalRelAttribute?: string;
  activeClass?: string;
  exactActiveClass?: string;
  trailingSlash?: 'append' | 'remove'
  prefetch?: boolean
  prefetchedClass?: string
  prefetchOn?: Partial<{
    visibility: boolean
    interaction: boolean
  }>
}
function defineNuxtLink(options: NuxtLinkOptions): Component {}
  • componentName: 컴포넌트 이름. 기본값은 NuxtLink입니다.
  • externalRelAttribute: 외부 링크에 적용할 기본 rel 속성 값. 기본값은 "noopener noreferrer"입니다. 비활성화하려면 ""로 설정
  • activeClass: 활성화된 링크에 적용할 기본 클래스. Vue Router의 linkActiveClass 옵션과 동일하게 동작합니다. 기본값은 Vue Router의 기본값("router-link-active")입니다.
  • exactActiveClass: 정확히 활성화된 링크에 적용할 기본 클래스. Vue Router의 linkExactActiveClass 옵션과 동일하게 동작합니다. 기본값은 Vue Router의 기본값("router-link-exact-active")입니다.
  • trailingSlash: href의 끝에 슬래시를 추가하거나 제거하는 옵션. 설정하지 않거나 유효한 값(append 또는 remove)이 아니면 무시됩니다.
  • prefetch: 기본적으로 링크를 프리페치할지 여부.
  • prefetchOn: 기본적으로 적용할 프리페치 전략을 세밀하게 제어합니다.
  • prefetchedClass: 프리페치된 링크에 적용할 기본 클래스.
Read and edit a live example in Docs > Examples > Routing > Pages.