vue-i18n,替代方案。$i18n 使用组合 API?

Run*_*set 10 vue.js vue-i18n vuejs3 vue-composition-api

尝试在具有组合 API 的组件中实现 vue-i18n。我希望能够在 onMounted 挂钩内设置一些翻译消息。在选项 api 中,我会使用this.$i18n.setLocaleMessage(locale, messages).

但是,this在组合 API 的 Setup() 方法中不可用。因此,当我尝试上述操作时,它给了我未定义的信息。我可以通过将 i18n 导入到组件中来做到这一点: import { useI18n } from 'vue-i18n'然后创建它的一个实例var i18n = useI18n({}), i18n.setLocaleMessage(),但我更喜欢像第一个这样的单行解决方案。

Bou*_*him 13

只需使用t如下useI18n

const {t} = useI18n({})
//then use in any place in the setup hook
onMounted(()=>console.log(t('someWord')) 
Run Code Online (Sandbox Code Playgroud)


小智 7

我在 Vue 2 中使用 @vue/composition-api 包时遇到了同样的问题。此设置需要 vue-i18n v8.x,它没有 useI18n 可组合项。

我很幸运地使用自己的 useI18n 函数创建了一个可组合项,该函数以 vue-i18n 创建者的这个函数为模型:https://github.com/intlify/vue-i18n-composable/blob/master/src/index.ts

他们的解决方案是使用 TypeScript,因此这里有一个翻译后的 JavaScript 版本,以防它对您有用:

/**
 * Adapted from https://github.com/intlify/vue-i18n-composable/tree/master/src
 * This is temporary to allow us to use VueI18n 8.x with the Composition API and Vue 2
 * Once we upgrade to Vue 3 (which allows an upgrade to VueI18n 9.x), we can remove this
 * in favor of VueI18n's useI18n() hook
 */

import { computed, getCurrentInstance } from '@vue/composition-api'
import Vue from 'vue'
import VueI18n from 'vue-i18n'

let i18nInstance = VueI18n

export function createI18n(options) {
  i18nInstance = new VueI18n(options)

  return i18nInstance
}

export function useI18n() {
  if (!i18nInstance) throw new Error('vue-i18n not initialized')

  const i18n = i18nInstance

  const instance = getCurrentInstance()
  const vm = instance?.proxy || instance || new Vue({})

  const locale = computed({
    get() {
      return i18n.locale
    },
    set(v) {
      i18n.locale = v
    }
  })

  return {
    locale,
    t: vm.$t.bind(vm),
    tc: vm.$tc.bind(vm),
    d: vm.$d.bind(vm),
    te: vm.$te.bind(vm),
    n: vm.$n.bind(vm)
  }
}
Run Code Online (Sandbox Code Playgroud)

我将其保存src/composables/useI18n.js并在单个文件组件中使用它,如下所示:

<template>
  <h1>{{ t('translate-me') }}</h1>
</template>


<script>
import { useI18n } from '@/composables/useI18n'

const i18n = {
  messages: {
    en: {
      : 'Finish Arranging Widgets',
    }
  }
}

export default {
  i18n,

  setup() {
    const { t } = useI18n()

    return { t }
  }
}
</script>
Run Code Online (Sandbox Code Playgroud)