【问题标题】:Switching between languages VueI18n切换语言 VueI18n
【发布时间】:2018-06-05 08:15:22
【问题描述】:

我正在使用 VueI18n 来支持网站中的两种语言,基于 VueJS,但现在我想在两种语言之间切换。你能帮帮我吗?

main.js:

import Vue from 'vue'
import VueI18n from 'vue-i18n'
import {messages} from './locales/bg_en_messages'

Vue.use(VueI18n)

const i18n = new VueI18n({
  locale: 'en', // set locale
  messages // set locale messages
});

const app = new Vue({
  i18n,
  el: '#app',
  render: h => h(App),
  router
})

./locales/bg_en_messages.js:

export const messages = {
  bg: {
    labels: {
      personName: 'Име на лицето'
    }
  },
  en: {
    labels: {
      personName: 'Name of person'
    }
  }
}

VueJS:

<label>{{ $t("labels.personName") }}</label>

我想放置一个下拉菜单或一个按钮,用于在两种语言之间切换。我正在查看 VueI18n 的文档,但没有太多信息,所以如果你能帮助我,我将不胜感激。 :)

更新帖子:

我让它可以切换语言。现在我还有一个关于 vueI18n 的 vue-good-table 的问题。

我有一张桌子:

<template>
  <vue-good-table
    :columns="columns"
    :rows="items"
    :paginate="true"
    :lineNumbers="true">
  </vue-good-table>
</template>

columns: [
          {
            label: 'Column1',
            field: 'column1',
            type: 'String',
            filterable: true,
            placeholder: 'Column1'
          },
          {
            label: 'Column2',
            field: 'column2',
            type: 'String',
            filterable: true,
            placeholder: 'Column2'
          },
          {
            label: 'Column3',
            field: 'column3',
            type: 'String',
            filterable: true,
            placeholder: 'Column3'
          },
          {
            label: 'Column3',
            field: 'column3',
            type: 'String',
            filterable: true,
            placeholder: 'Column3'
          }
        ]

我可以在 {{ $t("label.column1") }} 中添加标签吗?目前标签只接受字符串,但我也需要更改列的语言。

【问题讨论】:

    标签: vue.js switch-statement multilingual


    【解决方案1】:

    您可以尝试如下github issue 在您的 Vue 实例中创建一个 getter 和一个 setter:

    app.i18n = new VueI18n({
        locale: 'es',
        fallbackLocale: 'es',
        messages
      })
    
      Object.defineProperty(Vue.prototype, '$locale', {
        get: function () {
          return app.i18n.locale
        },
        set: function (locale) {
          app.i18n.locale = locale
        }
      })
    
      // this part happens later
    
     new Vue(app)
    

    然后在任何地方使用它:

    this.$locale // root Vuei18n locale    
    this.$locale = 'en' // set root Vuei18n locale
    // or
    this.$root.i18n.locale // root Vuei18n locale    
    this.$root.i18n.locale  = 'en' // set root Vuei18n locale
    

    【讨论】:

    • 我更新了我的第一篇文章以获取更多关于将其添加到 vue-good-table 列中的信息
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多