vue3 i18n 在组合式文件中使用 Must be called at the top of a `setup`

版本:VueI18n 9.x

问题:
在 单独的 文件中使用 useI18n() , 而不是在 setup() 中直接使用

const { locale } = useI18n({ useScope: 'global' })

一不小心,就会报错:

Must be called at the top of a `setup`

解决方法:
在 组合式文件中,引入自己创建的 i18n 对象

// i18n/index.ts

import { createI18n } from 'vue-i18n'
import enLocale from './en'
import zhLocale from './zh'

const messages = {
  en: {
    ...enLocale
  },
  zh: {
    ...zhLocale
  }
}

const i18n = createI18n({
  legacy: false,
  locale: 'en', // 设置默认语言
  fallbackLocale: 'en',
  messages: messages // 设置资源文件对象
})

export default i18n

组合式文件引入对象:

import i18n from '../i18n'
const { locale, t } = i18n.global

export function f() {
    console.log(locale.value)
    ....
}
posted @ 2022-08-26 10:59  zhanglw  阅读(3389)  评论(0编辑  收藏  举报