yoyojs
yoyojs

Reputation: 1773

Select element to get locale in nuxt with nuxt-i18n

I use nuxt-i18n nuxt-i18n documentation link to get different locales on my website like that :

<nuxt-link v-for="locale in $i18n.locales"
             v-if="locale.code !== $i18n.locale"
             :key="locale.code"
             :to="switchLocalePath(locale.code)"
             class="locales white--text"
  >{{ locale.code }}
  </nuxt-link>

And it works perfectly fine but i want to transform this code to render in a select element:

<select v-model="selected" class="locales white--text" @change=" ??? ">
    <option disabled value="">{{ $i18n.locale }}</option>
    <option v-for="locale in $i18n.locales" :key="locale.code">{{ locale.code }}</option>
  </select>

Locales strings appears well but i don't dind a solution to launch the switchLocalePath function on change. Is there a proper way to do that with nuxt (vue.js) ?

Upvotes: 5

Views: 5837

Answers (3)

mohammad
mohammad

Reputation: 31

In the first step, do the following first

// nuxt.config.js, inside nuxt-i18n module

locales: [
  { code: 'ar', iso: 'ar', file: 'ar/app.js', dir: 'rtl' },
  { code: 'en', iso: 'en-US', file: 'en/app.js', dir: 'ltr' },
  { code: 'fr', iso: 'fr-FR', file: 'fr/app.js', dir: 'ltr' },
],

Then create a plugin in the code and enter the following code

// plugins/ltr-rtl.js

export default function({ app }, inject) {
  const dir = () => app.i18n.locales.find((x) => x.code === app.i18n.locale)?.dir;
  inject( 'dir', dir);
}

And in the last step

<!-- layouts/default.vue -->

<div id="app" :dir="$dir()">
  My app here...
</div>

Upvotes: 0

Dacxj0
Dacxj0

Reputation: 161

Also there is no need to use the router to change the locale, the API can be used too using this.$i18n.setLocale(locale)

  <select v-model="activeLang" @change="changeLang" name="lang" id="">
    <option
      :selected="locale === activeLang"
      v-for="locale in locales"
      :key="locale"
      :value="locale"
    >
      {{ locale }}
    </option>
  </select>

changeLang(event) {
  this.$i18n.setLocale(event.target.value);
}

CodeSandbox here

Upvotes: 1

Enrique Aparicio
Enrique Aparicio

Reputation: 807

Here you are, the dropdown list and the onChange method:

 <select v-model="selectedValue" @change="onChange(selectedValue)">
        <option disabled value>Please select one</option>
        <option
          v-for="(locale, index) in $i18n.locales"
          :key="index"
          :value="locale.code"
        >{{locale.name}}</option>
      </select>
 methods: {
    onChange(event) {
      this.$router.replace(this.switchLocalePath(event));
    }
  }

If you want to check working I have build a CodeSandox Nuxt working here:

https://codesandbox.io/embed/codesandbox-nuxt-1bhug?fontsize=14&hidenavigation=1&theme=dark

Upvotes: 8

Related Questions