国际化i18n配置

  1. 安装依赖
 1npm install @nuxtjs/i18n
  1. 配置i18n
 1modules: [
 2    '@nuxtjs/i18n'
 3  ],
 4  i18n: {
 5    langDir: '../locales/',
 6    defaultLocale: 'zh',
 7    detectBrowserLanguage: {
 8      useCookie: true,
 9      cookieKey: 'i18n_redirected',
10      alwaysRedirect: true,
11      
12    },
13    
14    strategy: 'no_prefix',
15    locales: [
16      {
17        code: 'zh',
18        file: 'zh.ts',
19        name: '简体中文'
20      },
21      {
22        code: 'en',
23        file: 'en.ts',
24        name: 'English'
25      }
26    ]
27  }
  1. 使用i18n
    LanguageSwitcher.vue
 1<template>
 2  <div class="language-switcher">
 3    <select v-model="locale" @change="switchLanguage">
 4      <option 
 5        v-for="lang in availableLocales" 
 6        :key="lang.code" 
 7        :value="lang.code"
 8      >
 9        {{ lang.name }}
10      </option>
11    </select>
12  </div>
13</template>
14
15<script setup lang="ts">
16const { locale, locales } = useI18n()
17const switchLocalePath = useSwitchLocalePath()
18const router = useRouter()
19
20const availableLocales = computed(() => {
21  return (locales.value).map(l => {
22    return {
23      code: l.code,
24      name: l.name
25    }
26  })
27})
28
29const switchLanguage = () => {
30  const path = switchLocalePath(locale.value)
31  if (path) {
32    router.push(path).then(() => {
33      window.location.reload() // 强制刷新页面
34    })
35  }
36}
37</script>
38
39<style scoped lang="less">
40.language-switcher {
41  select {
42    padding: @spacing-sm @spacing-md;
43    border: 1px solid @border-color;
44    border-radius: @border-radius-md;
45    background-color: transparent;
46    color: @light-text-color;
47    cursor: pointer;
48
49    &:hover {
50      border-color: @secondary-color;
51    }
52
53    option {
54      padding: 10px;
55      background-color: @primary-color;
56      color: @light-text-color;
57    }
58  }
59}
60</style>
  1. 创建语言文件
    /locales/en.ts
 1export default {
 2  welcome: 'Welcome',
 3  nav: {
 4    home: 'Home',
 5    about: 'About'
 6  },
 7  content: {
 8    title: 'My Project',
 9    body: 'This is a project built with Nuxt3',
10    footer: '© 2024 All rights reserved'
11  },
12  sidebar: {
13    left: 'Left Sidebar',
14    right: 'Right Sidebar'
15  }
16}

/locales/zh.ts

 1export default {
 2  welcome: '欢迎',
 3  nav: {
 4    home: '首页',
 5    about: '关于'
 6  },
 7  content: {
 8    title: '我的项目',
 9    body: '这是一个使用 Nuxt3 构建的项目',
10    footer: '© 2024 版权所有'
11  },
12  sidebar: {
13    left: '左侧栏目',
14    right: '右侧栏目'
15  }
16}

在需要国际化的地方通过{{ $t(‘sidebar.right’) }}的形式来使用

运行项目后,可以引入切换按钮进行语言切换

 

 

ps:切换语言后需要刷新页面才会正确显示

个人笔记记录 2021 ~ 2025