How can Vue i18n v9 be utilized as a JavaScript object instead of embedding it within the template?

Can Vue and vue-i18n be used with JavaScript objects only, without being included in the template?

This code is located in src/boot/i18n.js

import { boot } from 'quasar/wrappers'
import { createI18n } from 'vue-i18n'
import messages from 'src/i18n'

export default boot(({ app }) => {
  const i18n = createI18n({
    locale: 'es-CO',
    fallbackLocale: 'en-US',
    globalInjection: true,
    messages
  })

  // Set i18n instance on app
  app.use(i18n)
})

I have created additional files like src/support/errors and utils where I need to insert messages but am unable to access i18n.

View image description here

As a native Spanish speaker and junior in Quasar Vue, any help would be greatly appreciated.

Thank you.

Answer №1

One of the easiest ways to handle this is by utilizing the built-in solution with the global property

import { boot } from 'quasar/wrappers'
import { createI18n } from 'vue-i18n'
import messages from 'src/i18n'

export const i18n = createI18n({
    locale: 'es-CO',
    fallbackLocale: 'en-US',
    globalInjection: true,
    messages
  })

export default boot(({ app }) => {
  // Assigning i18n instance to app
  app.use(i18n)
})


import { i18n } from "src/boot/i18n";

const { t } = i18n.global;

...
const customMessageByErrorType = (error) => {
  const messages = {
    401: t('httpErrors.error401'),
    403: t('httpErrors.error403'),
    ...
  }
  return messages[error.response.status]
}

Answer №2

This method worked for me, although I am not certain if it is the most efficient way to accomplish this task.

To start, you can define a variable in your store that contains an i18n instance and create a getter to access it:

import { boot } from 'quasar/wrappers'
import { createI18n } from 'vue-i18n'
import messages from 'src/i18n'
import {useCommonStore} from 'stores/all'

const $commonStore = useCommonStore()

export default boot(({ app }) => {
  const i18n = createI18n({
    locale: 'es-CO',
    fallbackLocale: 'en-US',
    globalInjection: true,
    messages
  })

  // Set i18n instance on app
  app.use(i18n)
  app.provide('i18n',i18n)
  app.config.globalProperties.$i18n = i18n
  $commonStore.$i18n = i18n
})

Next, you can create a Store like the following:

import {defineStore} from 'pinia'

export const commonStore = defineStore('common', {
  state: () => ({
    $i18n: {},
  }),
  getters: {
    i18n() {
      return this.$i18n.global;
    },
  },
  actions: {
    TRANSLATE(message) {
      return this.$i18n.global.t(message)
    }
  },
});

This setup allows you to utilize the i18n functionality in JavaScript files outside of components, as shown in the example below:

import { Notify } from 'quasar'
import {useCommonStore} from 'stores/all'

const $commonStore = useCommonStore()

// Rest of the code remains same with necessary adjustments.

I hope this code snippet proves useful for anyone seeking similar solutions.

Answer №3

When working with "vue-i18n" version "^9.13.1" and Vue 3, I encountered a need to use multiple languages outside the template component.

To achieve this, follow these steps:

Step 1: Export i18n from main.js ![Image Description](https://i.sstatic.net/65eb0YMB.png)

Step 2: Import { i18n } from '@/main' in your VUE file

Step 3: Access the t function from i18n:

const { t } = i18n.global

Step 4: Retrieve the message using t('key Message') in the vue file

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

How to ensure NodeJS waits for a response before returning a value

I've come across a seemingly simple problem that I just can't seem to solve. My current project involves working with an asynchronous messaging bot. In this particular scenario, the bot is supposed to react to an event by calling a Restful API a ...

SQL stores Array Input as a static identifier 'Array'

Previously, I was able to save an object in the database. However, now I need to save each individual data in an array within a row. I attempted to use array_column to store a specific set of data in a column, but it ended up saving as the word 'Array ...

Unique Javascript Library Focused on AJAX

Looking for a specific JavaScript library that focuses solely on AJAX functionality, such as a basic XMLHttp wrapper. ...

What steps can be taken to address the error message "FATAL: Unable to load template" encountered while using

I'm encountering the issues documented here and here on GitHub. I'm working on incorporating documentation for my Next.js code, and below is my jsdoc configuration file. { "tags": { "allowUnknownTags": true, "di ...

Combining a variety of animations within a mesh

Can someone help me understand this specific example in Three.js? The link is . I am facing some difficulties with the BlendCharacter.js file. this.load = function ( url, onLoad ) { var scope = this; var loader = new THREE.JSONLoader(); load ...

Tips for transferring a geolocation lat lng to the `ll` property of a different function in React

I have a Geolocation.js file that retrieves the geolocation data and logs it to the console. This file is imported into an index.js file and I need to use the lat and lng values that are logged to replace the hardcoded values in the ll parameter in the fol ...

Tips for ensuring equal height and width for a card using the <v-flex auto> component

I am in the process of organizing a set of cards, all of which need to be the same size. Check out an example I have created here: https://codepen.io/creativiousa/pen/BErpPb I attempted to modify my code using <v-card height='100%'> </ ...

The browsers Firefox and Internet Explorer are unable to perform ajax requests

Currently, I am utilizing jQuery version 3.3 in conjunction with the following Ajax script: <script type="text/javascript"> $(document).ready(function(){ $("form").submit(function(){ $.ajax({ url: 'msgs.p ...

How can I configure Select2 to begin searching alphabetically?

I'm currently using select2 for tag searching within my article tracking application, and I've noticed an issue. When typing 'm' or 'mi', the expected behavior would be for tags like 'migrations' to appear first. How ...

The image code is not recognizing the image source

In my attempt to dynamically set the image source in an HTML element after creating it with JavaScript, I have made some interesting observations through testing and alert messages: When providing the image src as a fixed filepath during the creation o ...

Is there a JavaScript equivalent to the explode function in PHP with similar functionality

I'm facing an issue while attempting to split my string in JavaScript, here is the code I am using: var str = 'hello.json'; str.slice(0,4); //output hello str.slice(6,9); //output json The problem arises when trying to slice the second str ...

Integrating jQuery plugin into a .vue file in Laravel: A step-by-step guide

I'm trying to incorporate the jQuery plugin scrollify into my Vue.js view within a Laravel project - how can this be achieved? I have already added the import in my master.blade.php file: <script src="{{asset('js/libs/jquery.scrollify.js ...

What is your preferred datepicker for Vue.js 2?

Can anyone recommend a Vue.js 2.0 date picker component that meets my specific needs? I'm in search of one with the following requirements: Ability to select a range - start date and end date. Easily customizable using CSS. Capability to trigger a m ...

The property mentioned was attempted to be accessed during the rendering process, however it is not defined on the instance

I am currently facing four main errors that I need to resolve while working with Vue 3: https://i.sstatic.net/23ir7.png Despite everything else working correctly, my code seems to have issues specifically with user inputs. //############--contact.js-- ...

npm ERR! Your operating system has denied the operation

When attempting to install create-react-app globally using 'npm install -g create-react-app', an error occurred due to insufficient write access to the /usr/local/lib/node_modules directory. The error message displayed was as follows ...

Juggling between setting state in React Native and saving in asyncStorage simultaneously

I have developed a react native app module that tracks health statistics, specifically focusing on weight. When the dashboard loads, there is an empty component with a button that opens an editor modal. This modal provides a text input where the user can e ...

Error encountered during Django ajax POST: CSRF token missing or incorrect

i am facing an issue sending a csv file and a bunch of data through ajax. I keep getting a Forbidden (CSRF token missing or incorrect) error even though I am sending the csrftoken. One more thing, I noticed that I am getting a different token in the code a ...

A step-by-step guide on integrating vuetify-component into codeceptjs

When attempting to write tests using codecept.js, I am facing difficulties accessing the vuetify components. <v-layout> <v-flex xs7> <v-text-field ref="video1min" v-model="video1min" :rules=" ...

Is it considered good practice to utilize Vue.js for managing global shared state and implementing for loops outside of components?

Just getting started with Vue.JS and experimenting with creating two lists of books (read and unread) from a shared object in the global data state. This is my approach - working demo (works like a charm! However, I'm wondering if this is considered ...

Upgrade from using a switch statement to a more robust pattern in JavaScript

I am looking to enhance my app by dynamically displaying pages based on a user's type and role properties. Currently, I am using a simple switch statement that determines the view based on the user's type, like this: switch(type) { case ' ...