Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
632 views
in Technique[技术] by (71.8m points)

vue.js - Locale keeps resetting between switching pages. Nuxt-i18n

I am trying to set up localization for my Nuxt frontend. Every time I switch to English and then move to an other subpage of my website it does reset back to German.

This is my LanguageSelector

<template>
  <div class="lang-dropdown">
    <select v-model="$i18n.locale">
      <option
        v-for="lang in $i18n.locales"
        :key="lang.code"
        :value="lang.code"
        onchange="changeLocale"
      >
        {{ lang.name }}
      </option>
    </select>
  </div>
</template>

This is my i18n config file

import de from '../locales/de.json'
import en from '../locales/en.json'

export default {
  local: 'en',
  fallbackLocale: 'de',
  messages: { de, en },
  strategy: 'prefix'
}

This is my buildModules section of the Nuxt.config.js

 ['nuxt-i18n',
      {
        defaultLocale: 'de',
        seo: true,
        locales: [
          {
            code: 'de',
            name: 'Deutsch',
            iso: 'de-DE'
          },
          {
            code: 'en',
            name: 'English',
            iso: 'en-US'
          }
        ],
        vueI18n: i18n
      }]
question from:https://stackoverflow.com/questions/65864526/locale-keeps-resetting-between-switching-pages-nuxt-i18n

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

according to this quote from nuxtjs/i18n docs

When using detectBrowserLanguage and wanting to persist locale on a route change, you must call one of the functions that update the stored locale cookie. Call either setLocaleCookie(locale) to persist just the cookie locale or setLocale(locale) to both persist the cookie locale and switch the route to the specified locale. Otherwise, locale might switch back to the saved one during navigation.

https://i18n.nuxtjs.org/lang-switcher

you should use $i18n.setLocale instead of changing the property locale
using setLocale will change the cookie that stores the chosen locale

in your case this code should work

<template>
  <div class="lang-dropdown">
    <select @change="(e) => $i18n.setLocale(e.target.value)">
      <option
        v-for="lang in $i18n.locales"
        :key="lang.code"
        :value="lang.code"
        onchange="changeLocale"
      >
        {{ lang.name }}
      </option>
    </select>
  </div>
</template>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...