vue.js - 语言之间切换 VueI18n

标签 vue.js switch-statement multilingual

我正在使用 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 的文档,但没有太多信息,所以如果您帮助我,我将不胜感激。 :)

更新帖子:

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

我有一张 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") }} 。目前标签仅接受字符串,但我也需要更改列的语言。

最佳答案

您可以尝试如下 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.js - 语言之间切换 VueI18n,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50695325/

相关文章:

javascript - 将焦点设置在第二级引导模式中包含的输入控件上

c# - 如何使用 Vue.js 和 .NET Core API 设置 Active Directory 身份验证

javascript - 在 vue.js 中保留 DOM 更新时的滚动位置

jqgrid全屏切换,窗口宽高

php - 如何根据域默认为另一种语言

javascript - 多语言支持

javascript - 使用 vuejs 而不使用指令的域特定语言

java - Switch case 需要两次调用才能实际工作

c# - 按位标志和 Switch 语句?

php - 使主题 wmpl 准备好 wpml-config