You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Nuxt i18n处理public目录下的多语言公共文件?

在Nuxt中用i18n处理public目录下的多语言文件

以你提到的作品集网站简历场景为例,支持英语(en)和法语(fr),对应public/resume.pdf和public/fr/cv.pdf,可以通过以下步骤用<NuxtLinkLocale>实现自动匹配语言的文件链接:

1. 确保i18n基础配置正确

先在nuxt.config.ts里配置好语言策略,这里推荐用prefix_except_default(默认语言不带路径前缀,其他语言带),适配你的文件结构:

export default defineNuxtConfig({
  modules: ['@nuxtjs/i18n'],
  i18n: {
    locales: [
      { code: 'en', iso: 'en-US', name: 'English' },
      { code: 'fr', iso: 'fr-FR', name: 'Français' }
    ],
    defaultLocale: 'en',
    strategy: 'prefix_except_default'
  }
})

2. 动态生成文件路径并结合NuxtLinkLocale

<NuxtLinkLocale>会自动根据当前语言环境拼接路径前缀,我们只需要根据locale返回对应的文件相对路径即可:

方法一:直接在模板中判断

适合简单场景,代码简洁:

<template>
  <NuxtLinkLocale :to="resumeFilePath">
    {{ $t('downloadResume') }} <!-- 可配合i18n多语言文案 -->
  </NuxtLinkLocale>
</template>

<script setup>
const { locale } = useI18n()

// 根据当前语言动态返回文件路径
const resumeFilePath = computed(() => {
  return locale.value === 'fr' ? '/cv.pdf' : '/resume.pdf'
})
</script>
  • 当语言为英语时,<NuxtLinkLocale>生成/resume.pdf,对应public/resume.pdf
  • 当语言为法语时,自动拼接前缀生成/fr/cv.pdf,对应public/fr/cv.pdf

方法二:用映射对象管理多语言文件

适合需要扩展多语言的场景,维护更方便:

<template>
  <NuxtLinkLocale :to="getLocalizedFile('resume')">
    {{ $t('downloadResume') }}
  </NuxtLinkLocale>
</template>

<script setup>
const { locale } = useI18n()

// 定义所有多语言文件的映射关系
const localizedFiles = {
  resume: {
    en: '/resume.pdf',
    fr: '/cv.pdf'
    // 后续加其他语言直接在这里新增即可
  }
}

// 获取当前语言对应的文件路径,默认 fallback 到英文
const getLocalizedFile = (fileKey) => {
  return localizedFiles[fileKey][locale.value] || localizedFiles[fileKey].en
}
</script>

3. 适配其他i18n策略

如果你的i18n策略是prefix(所有语言都带路径前缀),只需把英文简历放到public/en/resume.pdf,代码逻辑无需修改,<NuxtLinkLocale>会自动生成/en/resume.pdf和/fr/cv.pdf,对应public目录下的文件。

内容的提问来源于stack exchange,提问作者Curs3W4ll

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 22:48:11