Exploring the power of Vuejs3 with Internationalization and the Composition API

Currently, I am working on a frontend interface in VueJS and integrating i18n with Vuejs 3. While the normal implementation of i18n works fine, I encountered issues when trying to use it with the composition API.

In my main.js file, I have set up i18n as follows:

const i18n = createI18n({
    messages: {
        en: en,
        fr: fr
    },
    fallbackLocale: 'en',
    locale: localStorage.Language || navigator.language.split('-')[0] || 'en',
})
const app = createApp(App)


app.use(router)
app.use(i18n)

app.mount('#app')

I referred to the documentation which mentioned adding legacy:false for using the composition API. However, after making this change, my $t function stopped working. Further exploration led me to this solution:

const app = Vue.createApp({
  setup() {
    const { t } = VueI18n.useI18n() // call `useI18n`, and spread `t` from  `useI18n` returning
    return { t } // return render context that includes `t`
  }
})

The issue arises because my createApp is already initialized as:

const app = createApp(App)

This is the default implementation by VueJS. I attempted various modifications such as inserting setup before or after App, but nothing seemed to work. It appears I may be complicating things further.

Do you have any ideas on how to effectively integrate i18n with the composition API? My ultimate goal is to utilize $i18n within a component switchLanguage created using the composition API for language management and access to information.

I appreciate any assistance you can offer. Thank you.

Answer №1

You have already set up i18n in your application, specifically in the main.js file. This step is crucial.

The example provided in the documentation does not necessarily have to be implemented on the instance created within createApp. It can work in any component as long as you have initialized i18n in the main.(js|ts)

This method will function in any component where you require t:

import { useI18n } from "vue-i18n";

export default defineComponent({
  setup() {
    const { t } = useI18n();
    // you can now utilize t('some.text.to.be.translated')
    // t('some.text.to.be.pluralized', { n: 1 }, 1);

    return {
      // make `t` accessible in the <template>:
      t, 
    }
  },
  // if you need it within any method, computed property, or hook
  // especially if you are still using Options API
  computed() {
    someTranslatedText() {
      return useI18n().t('translate.me');
    }
  },
  methods: {
    methodNeedingTranslation() {
      const { t } = useI18n();
      // perform actions with `t`
    }
  }
})

On a side note: All $tc (pluralization) features have been integrated into t.

If you are upgrading an existing application and prefer not to replace all instances of $t and $tc with t throughout templates:

setup: () => ({ 
  $t: useI18n().t
  $tc: useI18n().t 
})

To have $t and $tc accessible in any component's <template>, without needing to import + expose them in <script> (or <script setup>):

import App from './App.vue'
import { useI18n } from 'vue-i18n'

const app = createApp(App);
app.config.globalProperties.$t = useI18n().t
  • If you still require them in <script>, import from 'vue-i18n', as demonstrated above.
  • $tc no longer serves a purpose in Vue3. If your templates are transitioning from Vue2, it would be advisable to replace all occurrences of $tc with $t. Alternatively, you could assign useI18n().t to both if you wish to avoid modifying the templates:
Object.assign(app.config.globalProperties, {
  $t: useI18n().t,
  $tc: useI18n().t
})  

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The type 'IProduct' cannot be assigned to type '[]'

Looking for help with dispatching events between parent and child components. Interfaces: export interface IProduct { id: string; name: string; price: string; image: string; inStock: number; fastDelivery: bo ...

Improving the method of accomplishing a task using AngularJS

Clicking on an item in the tobeclicked list will transfer the data to the find empty list. The goal is to locate an empty list and update it by cloning the image there. The actual values and lists will include images. When an image is clicked, the system s ...

What's preventing the mobx @computed value from being used?

Issue: The computed value is not updating accordingly when the observable it is referencing goes through a change. import {observable,computed,action} from 'mobx'; export default class anObject { // THESE WRITTEN CHARACTERISTICS ARE COMPUL ...

The event for closing the React Select MUI dropdown does not trigger when selecting multiple options

When multiple values are selected from the dropdown and clicked outside, the dropdown closes but the onClose event fails to trigger. I need to filter data based on the selections made in the dropdown. For example, looking at the image below, I want to dis ...

Issue encountered when attempting to batch delete documents within a subcollection: Error message displays "TypeError: n.indexOf is not a

When attempting to batch delete a document within a subcollection, I encounter some issues. There are scenarios where I may need to remove the same product document ID along with various history document IDs, or multiple product document IDs with differen ...

JavaScript Function Not Executed in Bottom Section

I've implemented AngularJS includes in my project. Below is the code snippet from my index.html: <!DOCTYPE html> <html ng-app=""> <head> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"> ...

Issues with AngularJS dirty validation for radio buttons not being resolved

I have encountered an issue with my form fields. The validation for the email field is working correctly, but the radio button field is not displaying any errors when it should. I am using angular-1.0.8.min.js and I cannot figure out why this is happenin ...

I'm receiving a typeerror when trying to access the uid property of null, even though I don't have any asynchronous code and the users are logged

I am currently working on developing a user profile edit page that redirects users to their unique profile after logging in. However, I keep encountering an error that says Uncaught (in promise) TypeError: Cannot read properties of null (reading 'uid& ...

A guide on extracting keywords from the tynt API using JavaScript

Looking to extract the inbound keyword from an API: What would be the best way to use JavaScript to extract and display the value of the inbound keyword from this API? ...

Listening for Events from Child Components in Vue.js

I am struggling to figure out how to send an event from a child component to its parent in order to change the view. Although I have been able to create and emit the event, my template does not seem to be properly registering it. I am working with Single ...

What are the best methods for adjusting the size of a game's

I create games using HTML5/CSS/JS, but I am struggling to figure out how to make them scale to different screen resolutions. It seems like a simple task, but I can't seem to grasp it. SOLVED var RATIO = 480 / 800; // Initial ratio. function resize() ...

What is the best way to include additional text in a dropdown menu?

I'm trying to add the text "Choose Country" in a drop-down list before the user selects their country. example1 Here is the line of code I used: <option data-hidden="true"> Choose Country </option> However, the phrase does ...

Making a Connection with Ajax in Django: Adding Friends

I have been exploring the capabilities of Django-Friends My goal is to make it so that when a user clicks on the add friend button, it either disappears or changes to say "Request sent". However, I am encountering an issue where the button does not disapp ...

Deciphering unidentified Json data

Having some trouble with an error in my note taker app built using expressjs. Everything was working fine until I tried to save a new note and it's throwing this error: SyntaxError: Unexpected token o in JSON at position 1 at JSON.parse () Here&apos ...

Navigating to native script, the method for extracting an ID from a link is revealed

Is there a way to extract the unique identifier from this URL: I want to retrieve the code "11E89887FABBC1D" when clicking on the link. Any suggestions? ...

bespoke theme background hue

I currently have material-ui@next installed and I am attempting to customize the background color of the theme. Here is what I have tried: const customizedTheme = createMuiTheme({ palette: createPalette({ type: 'light', primary: purple ...

The Great Gatsby - Unable to access property 'component---src-pages-index-jsx' due to its undefined nature

Attempting to transition my current ReactJS application with a WordPress backend to GatsbyJS has presented some challenges. As a newcomer to GatsbyJS, I diligently followed the setup instructions provided on their website for Windows 10. Despite a successf ...

Insert the ng-if directive into an element using a directive

I am working on an AngularJS directive that involves looking up col-width, hide-state, and order properties for a flexbox element based on its ID. I want to dynamically add an ng-if=false attribute to the element if its hide-state is true. Is there a way ...

The functionality of the button in my script is limited to a single use

Below is a simple code snippet that I wrote: HTML & CSS: <!DOCTYPE html> <html> <head> <title> JavaScript Console </title> <style> button { text-align:center; ...

Setting up Vite dev server to run through a port proxy path: A step-by-step guide

Exploring the use of Vite dev server in a cloud-based development setup where it's possible to serve on and connect to ports, but access must be through a proxy path. Instead of typing http://localhost:3000/index.html, the goal is to reach https://my ...