<NuxtLink>는 Vue Router의 <RouterLink> 컴포넌트와 HTML의 <a> 태그를 모두 대체할 수 있는 드롭인 교체 컴포넌트입니다. 링크가 내부 링크인지 외부 링크인지 지능적으로 판별하고, 사용 가능한 최적화(프리패칭, 기본 속성 등)를 적용하여 적절하게 렌더링합니다.이 예시에서는 애플리케이션의 다른 페이지로 링크하기 위해 <NuxtLink> 컴포넌트를 사용합니다.
<template>
<NuxtLink to="/about">About page</NuxtLink>
</template>
<!-- (Vue Router & Smart Prefetching) -->
<a href="/about">About page</a>
이 예시에서는 id 파라미터를 전달하여 ~/pages/posts/[id].vue 라우트로 링크합니다.
<template>
<NuxtLink :to="{ name: 'posts-id', params: { id: 123 } }">
Post 123
</NuxtLink>
</template>
<a href="/posts/123">Post 123</a>
to prop에 객체를 전달하면 <NuxtLink>는 쿼리 파라미터 처리에 대해 Vue Router의 동작을 그대로 상속합니다. 키와 값은 자동으로 인코딩되므로 encodeURI나 encodeURIComponent를 수동으로 호출할 필요가 없습니다.기본적으로 <NuxtLink>는 상대 라우트에 대해 Vue Router의 클라이언트 사이드 내비게이션을 사용합니다. /public 디렉터리의 정적 파일이나 동일 도메인에 호스팅된 다른 애플리케이션으로 링크할 때, 이들은 클라이언트 라우트의 일부가 아니기 때문에 예기치 않은 404 오류가 발생할 수 있습니다. 이런 경우, Vue Router의 내부 라우팅 메커니즘을 우회하기 위해 <NuxtLink>와 함께 external prop을 사용할 수 있습니다.
external prop은 해당 링크가 외부 링크임을 명시적으로 나타냅니다. <NuxtLink>는 링크를 표준 HTML <a> 태그로 렌더링합니다. 이를 통해 링크가 Vue Router의 로직을 우회하고 리소스를 직접 가리키도록 하여 올바르게 동작하도록 보장합니다.
PDF나 이미지와 같은 /public 디렉터리의 정적 파일에 대해서는, 링크가 올바르게 해석되도록 external prop을 사용하세요.
<template>
<NuxtLink
to="/example-report.pdf"
external
>
Download Report
</NuxtLink>
</template>
같은 도메인에 있는 다른 애플리케이션을 가리킬 때, external prop을 사용하면 올바른 동작을 보장할 수 있습니다.
<template>
<NuxtLink
to="/another-app"
external
>
Go to Another App
</NuxtLink>
</template>
external prop을 사용하거나 자동 처리를 활용하면 올바른 내비게이션을 보장하고, 예기치 않은 라우팅 문제를 피하며, 정적 리소스나 애플리케이션 간 시나리오와의 호환성을 향상시킬 수 있습니다.
이 예시에서는 웹사이트로 링크하기 위해 <NuxtLink> 컴포넌트를 사용합니다.
<template>
<NuxtLink to="https://nuxtjs.org">
Nuxt website
</NuxtLink>
<!-- <a href="https://nuxtjs.org" rel="noopener noreferrer">...</a> -->
</template>
rel and noRel Attributestarget 속성이 있는 링크나 절대 링크(예: http://, https://, //로 시작하는 링크)에는 기본적으로 noopener noreferrer 값의 rel 속성이 적용됩니다.
noopener는 오래된 브라우저의 보안 버그를 해결합니다.noreferrer는 연결된 사이트에 Referer 헤더를 보내지 않음으로써 사용자 프라이버시를 향상시킵니다.이러한 기본값은 SEO에 부정적인 영향을 주지 않으며, 모범 사례로 간주됩니다.
이 동작을 덮어써야 할 때는 rel 또는 noRel props를 사용할 수 있습니다.
<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 속성이 추가되는 것을 막는 데 사용할 수 있습니다.
<template>
<NuxtLink
to="https://github.com/nuxt"
no-rel
>
Nuxt GitHub
</NuxtLink>
<!-- <a href="https://github.com/nuxt">...</a> -->
</template>
noRel과 rel은 함께 사용할 수 없습니다. rel은 무시됩니다.Nuxt는 자동으로 스마트 프리패칭을 포함합니다. 이는 링크가 보일 때(기본값) 뷰포트 안에 있거나 스크롤될 때를 감지하고, 사용자가 링크를 클릭했을 때 바로 준비되도록 해당 페이지의 JavaScript를 미리 가져온다는 의미입니다. Nuxt는 브라우저가 바쁘지 않을 때만 리소스를 로드하며, 연결이 오프라인이거나 2g 연결만 있는 경우에는 프리패칭을 건너뜁니다.
<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: 링크에 마우스를 올리거나 포커스를 받을 때 프리패치합니다. 이 방식은 pointerenter와 focus 이벤트를 수신하여, 사용자가 상호작용 의도를 보일 때 리소스를 선제적으로 프리패치합니다.또한 객체를 사용하여 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를 사용한 크로스 오리진 프리패칭이 활성화됩니다.
export default defineNuxtConfig({
experimental: {
crossOriginPrefetch: true,
},
})
앱 전체의 모든 링크에 대해 프리패칭을 전역적으로 활성화/비활성화하는 것도 가능합니다.
export default defineNuxtConfig({
experimental: {
defaults: {
nuxtLink: {
prefetch: false,
},
},
},
})
external을 사용하지 않을 때, <NuxtLink>는 Vue Router의 모든 RouterLink props를 지원합니다.
to: 임의의 URL 또는 Vue Router의 route location 객체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: 링크를 언제 프리패치할지에 대한 커스텀 제어를 허용합니다. 가능한 옵션은 interaction과 visibility(기본값)입니다. { interaction: true, visibility: true }와 같이 객체를 전달하여 완전한 제어를 할 수도 있습니다. 이 prop은 prefetch가 활성화(기본값)되어 있고 noPrefetch가 설정되지 않았을 때만 사용됩니다.noPrefetch: 프리패칭을 비활성화합니다.prefetchedClass: 프리패치된 링크에 적용할 클래스입니다.target: 링크에 적용할 target 속성 값rel: 링크에 적용할 rel 속성 값. 외부 링크의 기본값은 "noopener noreferrer"입니다.nuxt.config에서 일부 <NuxtLink> 기본값을 덮어쓸 수 있습니다.
app.config나 app/ 디렉터리 등 다른 위치로 옮겨질 가능성이 높습니다.export default defineNuxtConfig({
experimental: {
defaults: {
nuxtLink: {
// default values
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> 기본값을 덮어쓸 수 있습니다.
export default defineNuxtLink({
componentName: 'MyNuxtLink',
/* 아래 시그니처에서 더 많은 내용을 확인하세요 */
})
그런 다음 새로운 기본값과 함께 <MyNuxtLink /> 컴포넌트를 일반적으로 사용할 수 있습니다.
defineNuxtLink Signatureinterface 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: 프리패치된 링크에 기본적으로 적용할 클래스입니다.