nuxt logo

문서 번역(비공식)

<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 패널을 확인하여 라우트 이름과 사용할 수 있는 매개변수를 확인하세요.

to 속성에 객체를 전달할 때, <NuxtLink>는 Vue Router의 쿼리 매개변수 처리를 상속받습니다. 키와 값은 자동으로 인코딩되므로 encodeURIencodeURIComponent를 수동으로 호출할 필요가 없습니다.

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

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

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

정적 파일로 링크 연결하기

PDF나 이미지와 같은 /public 디렉토리의 정적 파일에 대해서는 external 속성을 사용하여 링크가 올바르게 해석되도록 합니다.

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

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

동일한 도메인의 다른 애플리케이션을 가리킬 때, external 속성을 사용하여 올바른 동작을 보장합니다.

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

external 속성을 사용하거나 자동 처리를 신뢰하면 적절한 내비게이션을 보장하고, 예상치 못한 라우팅 문제를 피하며, 정적 리소스나 크로스 애플리케이션 시나리오와의 호환성을 향상시킵니다.

외부 라우팅

이 예제에서는 <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 속성을 사용할 수 있습니다.

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 속성은 절대 링크에 기본 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 속성을 사용하여 링크를 언제 프리페칭할지 제어할 수 있습니다.

<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>

이 구성은 요소가 뷰포트에 들어올 때 관찰하고 pointerenterfocus 이벤트를 수신합니다. 이는 불필요한 리소스 사용이나 중복 프리페칭을 초래할 수 있으며, 두 트리거가 다른 조건에서 동일한 리소스를 프리페칭할 수 있습니다.

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

크로스 오리진 프리페칭을 활성화하려면 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: Vue Router의 라우트 위치 객체 또는 URL
  • 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 }. 이 속성은 prefetch가 활성화된 경우(기본값) 및 noPrefetch가 설정되지 않은 경우에만 사용됩니다.
  • noPrefetch: 프리페칭을 비활성화합니다.
  • prefetchedClass: 프리페칭된 링크에 적용할 클래스.

Anchor

  • target: 링크에 적용할 target 속성 값
  • rel: 링크에 적용할 rel 속성 값. 외부 링크의 기본값은 "noopener noreferrer"입니다.

기본값은 덮어쓸 수 있습니다. 변경하려면 기본값 덮어쓰기를 참조하세요.

기본값 덮어쓰기

Nuxt 설정에서

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

이 옵션은 향후 app.config 또는 app/ 디렉토리로 이동될 가능성이 있습니다.

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: 프리페칭된 링크에 적용할 기본 클래스.
샘플 코드 편집 및 미리보기examples > routing > pages