Nuxt2中如何让NuxtLink生成带完整域名的绝对URL?
解决Nuxt2中NuxtLink生成带域名绝对路径的问题
问题根源
你错误使用了router.base配置——这个选项用于设置应用的基础子路径(比如部署在https://example.com/app/下时,设为'/app/'),而非完整域名。直接填入完整域名会导致路由拼接错误,生成/https://example.com/xxx这类无效路径。
解决方案分两种场景:
场景1:静态站点(使用nuxt generate生成静态文件部署)
直接在nuxt.config.js中配置generate.domain,这是Nuxt2为静态生成场景提供的原生解决方案,无需额外修改组件:
export default { generate: { domain: 'https://example.com' }, // 注意:router.base保持默认值'/'即可,不要填域名 router: { base: '/' } }
执行nuxt generate后,生成的所有HTML文件中,NuxtLink对应的<a>标签会自动带上完整域名,比如https://example.com/calculators/sip/。
场景2:服务端渲染(SSR)或需动态切换域名
如果是SSR部署,或者需要根据不同环境(开发/生产)动态切换域名,可通过自定义NuxtLink组件实现:
- 在
nuxt.config.js中配置全局可访问的站点域名:
export default { publicRuntimeConfig: { // 可通过环境变量动态设置,本地开发可留默认值 siteUrl: process.env.SITE_URL || 'https://example.com' }, router: { base: '/' } }
- 创建自定义组件
~/components/CustomNuxtLink.vue:
<template> <nuxt-link v-bind="$attrs" :to="resolveAbsoluteUrl(to)" > <slot /> </nuxt-link> </template> <script> export default { props: { to: { type: [String, Object], required: true } }, methods: { resolveAbsoluteUrl(to) { const siteUrl = this.$config.siteUrl // 已为绝对路径则直接返回 if (typeof to === 'string' && to.startsWith('http')) { return to } // 处理字符串路径 if (typeof to === 'string') { const normalizedPath = to.startsWith('/') ? to : `/${to}` return `${siteUrl}${normalizedPath}` } // 处理路由对象 if (to.path) { const normalizedPath = to.path.startsWith('/') ? to.path : `/${to.path}` return { ...to, path: `${siteUrl}${normalizedPath}` } } return to } } } </script>
- 在
nuxt.config.js中全局注册该组件,替换默认的NuxtLink:
export default { components: { 'nuxt-link': '~/components/CustomNuxtLink.vue' } }
之后所有页面中使用<nuxt-link>的地方,都会自动生成带完整域名的绝对路径<a>标签。
内容的提问来源于stack exchange,提问作者Yashwardhan Pauranik
相关产品推荐
相关产品推荐

