nuxt-i18n后备忽略的路由

时间:2020-02-18 16:22:03

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

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

nuxt.config.js

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

因此该页面无法使用法语。

我的lang开关看起来像这样-到目前为止很简单:

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 => (i.code !== this.$i18n.locale) && (this.$nuxt.$route.path !== this.switchLocalePath(i.code)) )

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

1 个答案:

答案 0 :(得分:0)

我已经解决了这个问题,只需在它周围包装一个附加功能即可

<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
  }
}
…

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