1

我正在关注有关如何更改语言的文档(https://nuxt-community.github.io/nuxt-i18n/lang-switcher.html),效果很好。但是,每当我设置detectBrowserLanguage.useCookie并设置为 true 时detectBrowserLanguage.alwaysRedirect,我nuxt.config.js都应该调用该this.$i18n.setLocaleCookie(locale)方法来保持更改(如文档所述)。

我唯一的问题是,我应该在哪里调用这个方法?

我当前的代码:

<nuxt-link
  class="px-6 py-2 block"
  :click="this.$i18n.setLocaleCookie(locale)"
  v-for="locale in availableLocales"
  :key="locale.code"
  :to="switchLocalePath(locale.code)">{{ locale.code.toUpperCase() }}

export default {
  computed: {
    availableLocales () {
      return this.$i18n.locales.filter(i => i.code !== this.$i18n.locale)
    }
  }
}

如您所见,我尝试this.$i18n.setLocaleCookie(locale)在链接的单击事件上运行,但我得到了Cannot read property '$i18n' of undefined

4

1 回答 1

-1

尝试在插件中调用它

export default async function ({app, store}) {
  // on change locale
  app.i18n.beforeLanguageSwitch = (oldLocale, newLocale) => {
    ...
  }
}

nuxt.config.js

  plugins: [
    '~/plugins/i18n.js'
  ],
于 2020-01-20T10:18:11.953 回答