【问题标题】:Where to execute method to persist locale change in nuxt-i18n?在哪里执行方法以在 nuxt-i18n 中持久更改语言环境?
【发布时间】:2020-04-19 01:52:15
【问题描述】:

我正在关注有关如何更改语言 (https://nuxt-community.github.io/nuxt-i18n/lang-switcher.html) 的文档,它工作得很好。但是,每当我将nuxt.config.js 中的detectBrowserLanguage.useCookiedetectBrowserLanguage.alwaysRedirect 设置为true 时,我都应该调用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

【问题讨论】:

  • 停止在您的模板中使用它,它应该可以工作并且点击也是一个事件,所以不是“:”而是“@”

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


【解决方案1】:

尝试在插件中调用它

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

nuxt.config.js

  plugins: [
    '~/plugins/i18n.js'
  ],

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-26
    • 1970-01-01
    • 2018-12-26
    • 2022-10-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多