6

I need to find a way to use the $t of i18n within the setup script for my vue project

my i18n file looks like this:

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

my main js look like this:

import i18n from './lang/settings'
const application = createApp({ 
            render: () => h(app, props) 
        })
application.use(i18n)

I can perfectly use $t() in the template to translate but I have no clue how to access the same method within <script setup></script>

Tomas Lucena
  • 1,204
  • 1
  • 14
  • 31

3 Answers3

17

The i18n resource and the related files need to be placed in the way you have mentioned in your question.

You can use it in this way I have Added everything in main.ts for better understanding. you can use it in this way

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');

In your component

<script lang="ts" setup>
import { useI18n } from "vue-i18n";
const { t } = useI18n();
let name = t('sample.item1');
</script>
<template>
  {{name}}
</template>
andreas
  • 16,357
  • 12
  • 72
  • 76
Tony Tom
  • 1,435
  • 1
  • 10
  • 17
  • 5
    This should be the accepted answer. I find it unbelievable that such a simple task is not specified in the official documentation with its own section... – Gaet Nov 18 '22 at 14:44
  • is there a way to use localePath also in the script setup tag? because useI18n() doesnt have an localePath attribute – raphiel Jul 19 '23 at 09:15
3

For Vue-i18n version 9

add legacy: false when creating the instance (main.js)

const i18n = VueI18n.createI18n({
  legacy: false, // you must set `false`, to use Composition API
  locale: 'ja',
  fallbackLocale: 'en',
  messages,
  // other options
})

and in your script setup

<script setup>
import { useI18n } from "vue-i18n";

const { t } = useI18n({ useScope: "global" });

// Something to do here ...

</script>

vue-i18n doc

Retnilps
  • 51
  • 6
0

NUXT3

Create lang folder in project root:

en-US.js

export default {
  readMore: "Read more",
};

Follow this for more info: https://v8.i18n.nuxtjs.org/guide/lazy-load-translations

You can import in your component:

const { t } = useI18n();

And use it:

let myElement = {
   text: t('readMore')
}