首页 > 解决方案 > nuxt-i18n:Lang Switcher 错误“对象可能是‘未定义’

问题描述

我想用 nuxt-i18n 插件在我的 nuxt 应用程序上构建一个语言切换器。重要说明是,我使用的是 TypeScript 而不是 JavaScript。

如文档(https://i18n.nuxtjs.org/lang-switcher)中所示,我在我的导航栏组件中实现了以下代码:

TheNavbar.vue

<template>
  <nav class="navbar">
    <div class="container">
      <div>
        <NuxtLink
          v-for="locale in availableLocales"
          :key="locale.code"
          :to="switchLocalePath(locale.code)">{{ locale.name }}
        </NuxtLink>
      </div>
    </div>
  </nav>
</template>

<script lang="ts">
import Vue from 'vue';

export default Vue.extend({
  name: "TheNavbar",
  computed: {
    availableLocales() {
      return this.$i18n.locales.filter(i => i.code !== this.$i18n.locale);
    }
  }
})

在我的应用程序中,此解决方案有效。但是控制台打印出以下两个错误:

 ERROR  ERROR in src/components/shared/TheNavbar.vue:25:14                                                                                                                                                       18:49:05
TS2532: Object is possibly 'undefined'.
    23 |   computed: {
    24 |     async availableLocales() {
  > 25 |       return this.$i18n.locales.filter(i => i?.code !== this.$i18n.locale);
       |              ^^^^^^^^^^^^^^^^^^
    26 |     }
    27 |   }
    28 | })


ERROR in src/components/shared/TheNavbar.vue:25:48
TS2339: Property 'code' does not exist on type 'string | LocaleObject'.
  Property 'code' does not exist on type 'string'.
    23 |   computed: {
    24 |     async availableLocales() {
  > 25 |       return this.$i18n.locales.filter(i => i?.code !== this.$i18n.locale);
       |                                                ^^^^
    26 |     }
    27 |   }
    28 | })

我在 nuxt.config.js 中的 i18n 配置:

  i18n: {
    locales: [
      {
        code: 'de',
        name: 'Deutsch',
      },
      {
        code: 'en',
        name: 'English'
      }
    ],
    defaultLocale: 'de',
    vueI18n: {
      fallbackLocale: 'de',
      messages: {
        de: {
          welcome: 'Willkommen'
        },
        en: {
          welcome: 'Welcome'
        }
      }
    }
  },

标签: typescriptnuxt.jsvue-i18nnuxt-i18n

解决方案


尝试这个:

<NuxtLink
   v-if="availableLocales"
   v-for="locale in availableLocales"
   :key="locale.code"
   :to="switchLocalePath(locale.code)">{{ locale.name }}
</NuxtLink>

推荐阅读