【问题标题】:Select element to get locale in nuxt with nuxt-i18n使用 nuxt-i18n 选择元素以获取 nuxt 中的语言环境
【发布时间】:2018-12-26 14:36:27
【问题描述】:

我使用 nuxt-i18n nuxt-i18n documentation link 在我的网站上获取不同的语言环境:

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

它工作得非常好,但我想将此代码转换为在选择元素中呈现:

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

语言环境字符串看起来不错,但我没有找到在更改时启动 switchLocalePath 函数的解决方案。有没有合适的方法用 nuxt (vue.js) 做到这一点?

【问题讨论】:

  • this.$router.push(this.switchLocalePath(locale.code));
  • 但这必须在每个选项元素中?
  • 我的错,你应该改用selected 值(在@change 处理程序中)。
  • 我说你需要在@change 函数中使用selected(模型)的值,因为它是select 级别上唯一可用的东西; locale.code 是对应 option 元素的属性。
  • 在我的脚本中我有这个方法:changeLocale() { this.$router.push(this.switchLocalePath(this.selected)); }

标签: vue.js html-select nuxt.js


【解决方案1】:

给你,下拉列表和 onChange 方法:

 <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));
    }
  }

如果你想检查工作,我已经构建了一个 CodeSandox Nuxt 在这里工作:

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

【讨论】:

  • 这对我很有用。
  • 我不明白这个问题怎么会得到更多的支持?该解决方案有效,它是该问题的唯一解决方案。 People are strange.
【解决方案2】:

另外不需要使用路由器来改变语言环境,API 也可以使用 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);
}

代码沙盒here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-10-24
    • 2019-09-01
    • 2020-04-19
    • 2019-08-06
    • 2018-11-12
    • 2022-07-29
    • 2012-03-25
    • 1970-01-01
    相关资源
    最近更新 更多