【问题标题】:Vue - Use i18n within the setup scriptVue - 在设置脚本中使用 i18n
【发布时间】:2022-08-09 05:11:33
【问题描述】:

我需要找到一种方法在我的vue 项目的安装脚本中使用i18n$t

我的 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> 中访问相同的方法

标签: vuejs3 vue-composition-api vue-i18n


【解决方案1】:

i18n 资源和相关文件需要按照您在问题中提到的方式放置。

你可以这样使用 为了更好地理解,我在 main.ts 中添加了所有内容。 你可以这样使用它

Main.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
  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>

【讨论】:

    猜你喜欢
    • 2020-02-23
    • 2019-08-29
    • 1970-01-01
    • 2022-10-23
    • 2023-01-11
    • 2019-10-14
    • 2022-11-20
    • 2019-04-19
    • 2021-06-02
    相关资源
    最近更新 更多