我需要找到一种方法在我的
$t
项目的设置脚本中使用 i18n
的 vue
我的 i18n 文件如下所示:
import { createI18n } from 'vue-i18n'
import en from './en';
import es from './es';
const messages = { en, es };
const locales = [
{ code: 'en', name: 'English' },
{ code: 'es', name: 'Español' }
];
const i18n = createI18n({
locales: locales,
defaultLocale: 'en',
fallbackLocale: 'en',
messages,
silentTranslationWarn: true,
silentFallbackWarn: true,
})
export default i18n
我的主要js看起来像这样:
import i18n from './lang/settings'
const application = createApp({
render: () => h(app, props)
})
application.use(i18n)
我可以完美地在模板中使用
$t()
进行翻译,但我不知道如何在<script setup></script>
中访问相同的方法
i18n 资源和相关文件需要按照您在问题中提到的方式放置。
你可以这样使用 为了更好地理解,我已经在 main.ts 中添加了所有内容。 你可以这样使用它
主要.ts
import { createApp } from 'vue';
import App from './App.vue';
import router from './router';
import { createI18n } from 'vue-i18n';
const i18n = createI18n({
locale: 'en', // set locale
legacy: false, // for latest vuei18n with compo API
messages: {
en: {
sample:{
item1: 'hello world'
}
}} // set locale messages
});
createApp(App).use(router).use(i18n).mount('#app');
在你的组件中
<script lang="ts" setup>
import { useI18n } from "vue-i18n";
const { t } = useI18n();
let name = t('sample.item1');
</script>
<template>
{{name}}
</template>
对于 Vue-i18n 版本 9
创建实例时添加
legacy: false
(main.js)
const i18n = VueI18n.createI18n({
legacy: false, // you must set `false`, to use Composition API
locale: 'ja',
fallbackLocale: 'en',
messages,
// other options
})
在你的脚本设置中
<script setup>
import { useI18n } from "vue-i18n";
const { t } = useI18n({ useScope: "global" });
// Something to do here ...
</script>
NUXT3
在项目根目录创建lang文件夹:
en-US.js
export default {
readMore: "Read more",
};
请关注此以获取更多信息:https://v8.i18n.nuxtjs.org/guide/lazy-load-translations
您可以导入您的组件:
const { t } = useI18n();
并使用它:
let myElement = {
text: t('readMore')
}