Vue 3 - useI18n - 未捕获的语法错误:必须在 `setup` 函数的顶部调用

问题描述 投票:0回答:1

我有一个无法解决的问题

useI18n
。无论我做什么,我都无法让 i18n 翻译正常工作,并且在我的控制台中永远看到此消息:

未捕获的语法错误:必须在

setup
函数的顶部调用

堆栈跟踪显示,它在调用

useI18n()
函数时发生,尽管它位于名为
setup
的函数内。堆栈跟踪的下一个级别显示,在“useI18n()”函数中,由于未检测到我的应用程序的实例,因此引发了异常。

function useI18n(options = {}) {
    const instance = getCurrentInstance();
    if (instance == null) {
        throw createI18nError(I18nErrorCodes.MUST_BE_CALL_SETUP_TOP);
    }
...

我的代码如下:

main.js

// frontend/src/main.ts

import i18n from './i18n';

import Vue, { createApp } from 'vue';

import axios from 'axios';
import VueAxios from 'vue-axios';

import App from './App.vue';

//Vue.use(VueI18n);

const app = createApp(App);
app.use(VueAxios, axios, i18n);
app.provide('axios', app.config.globalProperties.axios);
app.mount('#i-english-editor');

console.log(app);

i18n.ts

import { createI18n } from "vue-i18n";

const i18n = createI18n({
  legacy: false,
  locale: "ja",
  fallbackLocale: 'en',
  globalInjection: true,
  messages: {
    en: {
      message: {
        language: "English",
        greeting: "Hello !"
      }
    },
    ar: {
      message: {
        language: "العربية",
        greeting: "السلام عليكم"
      }
    },
    es: {
      message: {
        language: "Español",
        greeting: "Hola !"
      }
    }
  }
});

export default i18n;

应用程序.vue

<div>
{{ t('message.greeting') }}
</div>
...
<script lang="ts">
import {defineComponent, ref, inject} from "vue";
import { useI18n } from "vue-i18n";

export default defineComponent({
  setup() {
    const { t } = useI18n();

...


    return {
      ...
      {t},
    }
  }
});
</script>

如您所见,我的代码看起来像在线的各种示例,向我展示如何使翻译工作。我查看了各种解决方案,但没有一个对我有用。这包括尝试另一种方法,将

globalInjection
设置为
true
并在显示错误的标签中使用
{{ $t('message.greeting') }}

ctx.$t 不是函数

我确实陷入了死胡同,无法找出似乎对大多数人都有效的解决方案。我的 Vue 版本是 Vue 3,我使用的 i18n 版本是 [email protected]

如果有人知道为什么这种情况发生在我身上,但没有人知道,如果你有解决方案,我将不胜感激。

vue.js translation i18next
1个回答
0
投票

更新 - 我设法解决了它。

首先,我不再需要使用

useI18n
函数,并意识到
$t
由于同一
app.use(...)
函数中的多次导入而失败。

我把它改为:

app.use(VueAxios, axios);
app.use(i18n as any);

app.use
向控制台抛出更多错误,因为
i18n
不是可接受的类型。为了解决这个问题,我从另一篇文章的解决方案中发现,添加
as any
是解决这个问题的一种方法。结果
{{ $t(...) }}
现在正在产生所需的结果。

© www.soinside.com 2019 - 2024. All rights reserved.