Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue - Use i18n within the setup script

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>

like image 514
Tomas Lucena Avatar asked Nov 24 '25 23:11

Tomas Lucena


2 Answers

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

In your component

<script lang="ts" setup>
import { useI18n } from "vue-i18n";
const { t } = useI18n({ useScope: "global" });
let name = t('sample.item1');
</script>
<template>
  {{name}}
</template>
like image 92
Tony Tom Avatar answered Nov 28 '25 16:11

Tony Tom


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

like image 25
Retnilps Avatar answered Nov 28 '25 16:11

Retnilps



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!