feat(nuxt): expose useLink from NuxtLink (#26522)

This commit is contained in:
Joaquín Sánchez 2024-04-19 11:48:49 +02:00 committed by GitHub
parent 3e610df4dd
commit 4dbe748cfc
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
4 changed files with 177 additions and 50 deletions

View File

@ -7,7 +7,7 @@ import type {
VNodeProps,
} from 'vue'
import { computed, defineComponent, h, inject, onBeforeUnmount, onMounted, provide, ref, resolveComponent } from 'vue'
import type { RouteLocation, RouteLocationRaw, Router, RouterLinkProps } from '#vue-router'
import type { RouteLocation, RouteLocationRaw, Router, RouterLink, RouterLinkProps, useLink } from '#vue-router'
import { hasProtocol, joinURL, parseQuery, parseURL, withTrailingSlash, withoutTrailingSlash } from 'ufo'
import { preloadRouteComponents } from '../composables/preload'
import { onNuxtReady } from '../composables/ready'
@ -120,6 +120,79 @@ export function defineNuxtLink (options: NuxtLinkOptions) {
return resolvedPath
}
function useNuxtLink (props: NuxtLinkProps) {
const router = useRouter()
const config = useRuntimeConfig()
// Resolving `to` value from `to` and `href` props
const to: ComputedRef<string | RouteLocationRaw> = computed(() => {
checkPropConflicts(props, 'to', 'href')
const path = props.to || props.href || '' // Defaults to empty string (won't render any `href` attribute)
return resolveTrailingSlashBehavior(path, router.resolve)
})
// Lazily check whether to.value has a protocol
const isAbsoluteUrl = computed(() => typeof to.value === 'string' && hasProtocol(to.value, { acceptRelative: true }))
// Resolves `to` value if it's a route location object
const href = computed(() => (typeof to.value === 'object'
? router.resolve(to.value)?.href ?? null
: (to.value && !props.external && !isAbsoluteUrl.value)
? resolveTrailingSlashBehavior(joinURL(config.app.baseURL, to.value), router.resolve) as string
: to.value
))
const builtinRouterLink = resolveComponent('RouterLink') as string | typeof RouterLink
const useBuiltinLink = builtinRouterLink && typeof builtinRouterLink !== 'string' ? builtinRouterLink.useLink : undefined
const link = useBuiltinLink?.({
...props,
to: to.value,
})
const hasTarget = computed(() => props.target && props.target !== '_self')
// Resolving link type
const isExternal = computed<boolean>(() => {
// External prop is explicitly set
if (props.external) {
return true
}
// When `target` prop is set, link is external
if (hasTarget.value) {
return true
}
// When `to` is a route object then it's an internal link
if (typeof to.value === 'object') {
return false
}
return to.value === '' || isAbsoluteUrl.value
})
return {
to,
hasTarget,
isAbsoluteUrl,
isExternal,
//
href,
isActive: link?.isActive ?? computed(() => to.value === router.currentRoute.value.path),
isExactActive: link?.isExactActive ?? computed(() => to.value === router.currentRoute.value.path),
route: link?.route ?? computed(() => router.resolve(to.value)),
async navigate () {
await navigateTo(href.value, { replace: props.replace, external: props.external })
},
} satisfies ReturnType<typeof useLink> & {
to: ComputedRef<string | RouteLocationRaw>
hasTarget: ComputedRef<boolean | null | undefined>
isAbsoluteUrl: ComputedRef<boolean>
isExternal: ComputedRef<boolean>
}
}
return defineComponent({
name: componentName,
props: {
@ -207,43 +280,11 @@ export function defineNuxtLink (options: NuxtLinkOptions) {
required: false,
},
},
useLink: useNuxtLink,
setup (props, { slots }) {
const router = useRouter()
const config = useRuntimeConfig()
// Resolving `to` value from `to` and `href` props
const to: ComputedRef<string | RouteLocationRaw> = computed(() => {
checkPropConflicts(props, 'to', 'href')
const path = props.to || props.href || '' // Defaults to empty string (won't render any `href` attribute)
return resolveTrailingSlashBehavior(path, router.resolve)
})
// Lazily check whether to.value has a protocol
const isAbsoluteUrl = computed(() => typeof to.value === 'string' && hasProtocol(to.value, { acceptRelative: true }))
const hasTarget = computed(() => props.target && props.target !== '_self')
// Resolving link type
const isExternal = computed<boolean>(() => {
// External prop is explicitly set
if (props.external) {
return true
}
// When `target` prop is set, link is external
if (hasTarget.value) {
return true
}
// When `to` is a route object then it's an internal link
if (typeof to.value === 'object') {
return false
}
return to.value === '' || isAbsoluteUrl.value
})
const { to, href, navigate, isExternal, hasTarget, isAbsoluteUrl } = useNuxtLink(props)
// Prefetching
const prefetched = ref(false)
@ -323,14 +364,6 @@ export function defineNuxtLink (options: NuxtLinkOptions) {
)
}
// Resolves `to` value if it's a route location object
// converts `""` to `null` to prevent the attribute from being added as empty (`href=""`)
const href = typeof to.value === 'object'
? router.resolve(to.value)?.href ?? null
: (to.value && !props.external && !isAbsoluteUrl.value)
? resolveTrailingSlashBehavior(joinURL(config.app.baseURL, to.value), router.resolve) as string
: to.value || null
// Resolves `target` value
const target = props.target || null
@ -353,15 +386,13 @@ export function defineNuxtLink (options: NuxtLinkOptions) {
return null
}
const navigate = () => navigateTo(href, { replace: props.replace, external: props.external })
return slots.default({
href,
href: href.value,
navigate,
get route () {
if (!href) { return undefined }
if (!href.value) { return undefined }
const url = parseURL(href)
const url = parseURL(href.value)
return {
path: url.pathname,
fullPath: url.pathname,
@ -372,7 +403,7 @@ export function defineNuxtLink (options: NuxtLinkOptions) {
matched: [],
redirectedFrom: undefined,
meta: {},
href,
href: href.value,
} satisfies RouteLocation & { href: string }
},
rel,
@ -383,7 +414,8 @@ export function defineNuxtLink (options: NuxtLinkOptions) {
})
}
return h('a', { ref: el, href, rel, target }, slots.default?.())
// converts `""` to `null` to prevent the attribute from being added as empty (`href=""`)
return h('a', { ref: el, href: href.value || null, rel, target }, slots.default?.())
}
},
}) as unknown as DefineComponent<NuxtLinkProps>

View File

@ -771,6 +771,43 @@ describe('nuxt links', () => {
await page.waitForFunction(() => window.scrollY === 0)
await page.close()
})
it('useLink works', async () => {
const html = await $fetch('/nuxt-link/use-link')
expect(html).toContain('<div>useLink in NuxtLink: true</div>')
expect(html).toContain('<div>route using useLink: /nuxt-link/trailing-slash</div>')
expect(html).toContain('<div>href using useLink: /nuxt-link/trailing-slash</div>')
expect(html).toContain('<div>useLink2 in NuxtLink: true</div>')
expect(html).toContain('<div>route2 using useLink: /nuxt-link/trailing-slash</div>')
expect(html).toContain('<div>href2 using useLink: /nuxt-link/trailing-slash</div>')
expect(html).toContain('<div>useLink3 in NuxtLink: true</div>')
expect(html).toContain('<div>route3 using useLink: /nuxt-link/trailing-slash</div>')
expect(html).toContain('<div>href3 using useLink: /nuxt-link/trailing-slash</div>')
})
it('useLink navigate importing NuxtLink works', async () => {
const page = await createPage('/nuxt-link/use-link')
await page.waitForFunction(() => window.useNuxtApp?.()._route.fullPath === '/nuxt-link/use-link')
await page.locator('#button1').click()
await page.waitForFunction(path => window.useNuxtApp?.()._route.fullPath === path, '/nuxt-link/trailing-slash')
await page.close()
})
it('useLink navigate using resolveComponent works', async () => {
const page = await createPage('/nuxt-link/use-link')
await page.waitForFunction(() => window.useNuxtApp?.()._route.fullPath === '/nuxt-link/use-link')
await page.locator('#button2').click()
await page.waitForFunction(path => window.useNuxtApp?.()._route.fullPath === path, '/nuxt-link/trailing-slash')
await page.close()
})
it('useLink navigate using resolveDynamicComponent works', async () => {
const page = await createPage('/nuxt-link/use-link')
await page.waitForFunction(() => window.useNuxtApp?.()._route.fullPath === '/nuxt-link/use-link')
await page.locator('#button3').click()
await page.waitForFunction(path => window.useNuxtApp?.()._route.fullPath === path, '/nuxt-link/trailing-slash')
await page.close()
})
})
describe('head tags', () => {

View File

@ -0,0 +1,53 @@
<script setup lang="ts">
import { resolveDynamicComponent } from 'vue'
import { NuxtLink } from '#components'
const useLinkPresent = 'useLink' in NuxtLink
const link = useLinkPresent ? NuxtLink.useLink({ to: '/nuxt-link/trailing-slash' }) : undefined
const route = computed(() => link?.route.value.path)
const href = computed(() => link?.href.value)
const NuxtLink2 = resolveComponent('NuxtLinkAlias') as unknown as any
const useLink2Present = typeof NuxtLink2 !== 'string' && 'useLink' in NuxtLink2
const link2 = useLink2Present ? NuxtLink2.useLink({ to: '/nuxt-link/trailing-slash' }) : undefined
const route2 = computed(() => link2?.route.value.path)
const href2 = computed(() => link2?.href.value)
const NuxtLink3 = resolveDynamicComponent('NuxtLinkAlias') as unknown as any
const useLink3Present = typeof NuxtLink3 !== 'string' && 'useLink' in NuxtLink3
const link3 = useLink3Present ? NuxtLink3.useLink({ to: '/nuxt-link/trailing-slash' }) : undefined
const route3 = computed(() => link3?.route.value.path)
const href3 = computed(() => link3?.href.value)
</script>
<template>
<div>
<div>useLink in NuxtLink: {{ useLinkPresent }}</div>
<div>route using useLink: {{ route }}</div>
<div>href using useLink: {{ href }}</div>
<button
id="button1"
@click="link?.navigate()"
>
Test
</button>
<div>useLink2 in NuxtLink: {{ useLink2Present }}</div>
<div>route2 using useLink: {{ route2 }}</div>
<div>href2 using useLink: {{ href2 }}</div>
<button
id="button2"
@click="link2?.navigate()"
>
Test
</button>
<div>useLink3 in NuxtLink: {{ useLink3Present }}</div>
<div>route3 using useLink: {{ route3 }}</div>
<div>href3 using useLink: {{ href3 }}</div>
<button
id="button3"
@click="link3?.navigate()"
>
Test
</button>
</div>
</template>

View File

@ -0,0 +1,5 @@
import { NuxtLink } from '#components'
export default defineNuxtPlugin((nuxtApp) => {
nuxtApp.vueApp.component('NuxtLinkAlias', NuxtLink)
})