Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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) ?

like image 295
yoyojs Avatar asked Jul 18 '18 15:07

yoyojs


2 Answers

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

like image 90
Enrique Aparicio Avatar answered Oct 23 '22 14:10

Enrique Aparicio


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

like image 35
Dacxj0 Avatar answered Oct 23 '22 12:10

Dacxj0