【问题标题】:Get current locale in a child component获取子组件中的当前语言环境
【发布时间】:2019-06-22 22:36:05
【问题描述】:

我无法在我的子组件中从 vue-i18n 获取语言环境参数。

我已经在 cli ui 中安装了 vue-i18n。使用 $t("message") 的翻译正在工作,但是当我尝试访问 i18n.locale 时出现错误

我的输入点(main.js)

    import Vue from 'vue'
    import App from './App.vue'
    import router from './router'
    import i18n from './i18n'

    new Vue({
      router,
      i18n,
      render: h => h(App)
    }).$mount('#app')

我的子组件

<template>
    <div>{{ $t("message") }}</div>
</template>
<script>
import {HTTP} from '@/http-common'

export default 
{
  name : 'c1',
  methods:{
      selectMap()
      {
          console.log(i18n.locale);//=> doesn't work
      }
}
</script>

i18n.js

import Vue from 'vue'
import VueI18n from 'vue-i18n'

Vue.use(VueI18n)

function loadLocaleMessages () {
  const locales = require.context('./locales', true, /[A-Za-z0-9-_,\s]+\.json$/i)
  const messages = {}
  locales.keys().forEach(key => {
    const matched = key.match(/([A-Za-z0-9-_]+)\./i)
    if (matched && matched.length > 1) {
      const locale = matched[1]
      messages[locale] = locales(key)
    }
  })
  return messages
}

export default new VueI18n({
  locale: process.env.VUE_APP_I18N_LOCALE || 'en',
  fallbackLocale: process.env.VUE_APP_I18N_FALLBACK_LOCALE || 'en',
  messages: loadLocaleMessages()
})

【问题讨论】:

  • 应该是console.log(this.$i18n.locale) kazupon.github.io/vue-i18n/api/#injected-properties
  • 我收到此错误Cannot read property '$i18n' of undefined
  • 这意味着您正在尝试在 this 不是 vue 实例的上下文中访问 this.$i18n。如果您尝试在子组件的方法之一中访问它,则不应如此。但是,您的子组件示例代码中的 methods 对象没有右括号,并且该组件通常看起来不完整。所以,我假设你没有从那个上下文中调用它。
  • 你说得对,我试图简化代码并没有以正确的方法调用 this.$i18n。现在一切正常,感谢您的帮助!

标签: vue.js vue-i18n


【解决方案1】:

试试this.$i18n.locale,或者如果在&lt;template&gt;里面,就试试$i18n.locale

【讨论】:

    猜你喜欢
    • 2017-04-11
    • 1970-01-01
    • 1970-01-01
    • 2014-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多