【问题标题】:nuxt-i18n fallback ignored routesnuxt-i18n 回退忽略路由
【发布时间】:2020-06-02 17:37:59
【问题描述】:

我有一个使用 nuxt-i18n 并忽略路由的多语言 Nuxt 应用程序。

nuxt.config.js

…
seo: true,
parsePages: false,
strategy: 'prefix_except_default',
pages: {
  'cats': {
    en: '/cats',
    de: '/katzen',
    fr: false
  }
}
…

所以该页面没有法语版本。

我的语言开关看起来像这样——到目前为止非常简单:

LanguageSwitch.vue

computed: {
  availableLocales () {
    return this.$i18n.locales.filter(i => i.code !== this.$i18n.locale)
  }
}
<ul class="language-switch__list">
  <li class="language-switch__item" v-for="locale in availableLocales">
    <NuxtLink
     class="language-switch__link"
     rel="alternate" :key="locale.code"
     :to="switchLocalePath(locale.code)"
     :hreflang="locale.code" :lang="locale.code"
     active-class="none"
     exact>
     {{locale.name}}
    </NuxtLink>
  </li>
</ul>

我已更改过滤器以删除类似这样的缺失页面/语言:

return this.$i18n.locales.filter(i =&gt; (i.code !== this.$i18n.locale) &amp;&amp; (this.$nuxt.$route.path !== this.switchLocalePath(i.code)) )

这行得通,但我想要一个更好的解决方案。这是我的问题:如果忽略路由,是否有一种简单的方法可以更改语言主页(/、/en、/de)的路由?

【问题讨论】:

    标签: vue.js nuxt.js vue-i18n nuxt-i18n


    【解决方案1】:

    我已经解决了这个问题,只需在它周围添加一个附加函数:

    <nav id="language-switch" v-if="isOpen" class="language-switch__nav arrow arrow--top">
      <ul class="language-switch__list">
        <li class="language-switch__item" v-for="locale in availableLocales">
          <NuxtLink class="language-switch__link" rel="alternate" :key="locale.code" :to="switchLocalePathFallback(locale.code)" :hreflang="locale.code" :lang="locale.code" active-class="none" exact>{{locale.name}}</NuxtLink>
        </li>
      </ul>
    </nav>
    
    …
    computed: {
      availableLocales () {
        return this.$i18n.locales.filter(i => (i.code !== this.$i18n.locale) )
      }
    },
    methods: {
      switchLocalePathFallback(code) {
        let langPath = this.switchLocalePath(code),
            path = langPath
        if(langPath == this.$nuxt.$route.path ) {
          path = this.$i18n.defaultLocale != code ? '/'+code : '/'
        }
        return path
      }
    }
    …
    

    不是很灵活,但对我有用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-08
      • 2019-01-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-31
      • 2013-08-02
      • 2019-12-25
      相关资源
      最近更新 更多