Guide to implementing translation in utility functions in Vue3

Utilizing translations with vue-i18n in my Vue application has been a smooth process (). My main.ts setup appears as follows:

// Setting up the Vue app
const app = createApp(App)

// Incorporating necessary plugins
app.use(i18n)
....

// Mounting the Vue app
app.mount('#app')

Translations are successfully implemented within my components, making everything run seamlessly.

Recently, I've been looking to develop a helper function for formatting durations into a more human-readable format at various points in my app - such as displaying "4 minutes, 2 seconds" in English and "4 Minuten, 2 Sekunden" in German.

To achieve this, I created a helper function in a separate file:

export default {
  formatDuration: (value: number) => {
    if (!value){
        return null;
    }
    
    let duration = dayjs.duration(value, "seconds");
    let secondsPart = duration.seconds();
    let minutesPart = duration.minutes();
    return (duration + " " + $t("seconds")); // encountering a build error
  }
}

The compilation issue arises on the last line due to the absence of $t. I am searching for a way to access the translation system and retrieve a string based on the current language without being within a vue component context.

Answer №1

To incorporate internationalization in your TypeScript helper file, include the following code:

import i18nInstance from "@/modules/i18n"
import { Composer } from "vue-i18n"

function translate(key: string): string {
  const translation = i18nInstance.global.t as Composer<{}, {}, {}, true>["t"]
  return translation(key)
}

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 JSX component in next.js cannot be utilized as a user component

I am facing difficulty in getting my mobile menu to function properly. Initially, I attempted to position it above other content using the useEffect hook, but unfortunately, it resulted in breaking the entire project. This is the error message I encountere ...

Verification function in cypress to ensure accurate display of specific timeframes

Looking to create a Cypress method for checking three different rounding cases regarding the hour. An example of the second case I want to include in a general method, if a specific argument is provided: ( cy.contains('00') && cy.contain ...

VueJS - optimizing build process eliminates attribute quotes in HTML code

Is it common practice to remove attribute quotes from HTML in a minified production build? Could this potentially cause issues with certain browsers or platforms? Regardless, I'm interested to learn more. I currently have the following configuration ...

Trouble with v-form and v-text-field components in Vue CLI 3.0

Currently, I am working on a project using Vue Cli 3 and have decided to implement Vuetify for its UI. To integrate Vuetify into Vue Cli 3, all I had to do was run the command: vue add vuetify While I can easily use features like v-layout and v-button, I ...

The seamless merging of Angular2, TypeScript, npm, and gulp for enhanced development efficiency

I'm fairly new to front-end development and I am currently working on an application using Angularjs2 with TypeScript in Visual Studio 2015. I have been following the steps outlined in this Quickstart https://angular.io/docs/ts/latest/cookbook/visual- ...

Creating Vue Component Templates

I am trying to add a dynamic class attribute within the template using a custom component: Vue.component('cards',{ props:['element'], template:'<div v-bind:class="\'item\' ...

Instructions on activating dark mode with the darkreader plugin on a Vue.js website

Is there a way to implement DarkMode in a Vue.js application? I attempted to integrate darkmode using this npm package, but I kept encountering the error message: DarkMode not defined. ...

Mastering the art of typing a member of an abstract generic class in Typescript with consideration for potential additional implementations

It's quite challenging to put into words, but essentially I aim to create a base abstract class outlining an abstract interface that must vary based on whether a derived class implements a specific interface or not. Here is a TypeScript playground de ...

What methods should I employ to effectively test a custom icon function?

I've written a function that creates a Leaflet icon with specified properties: createIcon( url, retinaUrl: string = null, height: number = 20, width: number = 20 ): Icon { const icon: Icon = L.icon({ iconUrl: url, ico ...

Efficient Ways to Store Text and Images in Vue.js

I have developed a tool that enables users to upload an image and overlay custom text on it, which can be viewed and edited in the browser. My query is whether it is feasible to save the combined image and text as separate files (e.g., jpg/png) using VueJS ...

Arrange an array of integers and letters alphabetically in an Angular/Typescript environment

My Sorting Strategy I am attempting to organize an array in the following manner... 1 2 2(a) 2(b) 2(b) #AsimpleName 2(b) #NameWithN 3 4 4(a) ... ... using Angular 2. Snippet of My Code Component this.streetDetailRef = this.afDatabase.list('data/us ...

Tips for accessing a store within the mounted() lifecycle method using NUXT.js

I am currently working on a project using NUXT.js and Open Street Map. I encountered an issue where I needed to access the store in the mounted() method, but received an error stating that the store was not defined within the namespace of the mounted() met ...

"Looking to efficiently sort an array in Vue3 - any suggestions on how to

Just starting out with Vue3 and running into an issue. I'm working on filtering an array to get items with the same value, then adding those results to another array. This is the array I'm dealing with: let list = [ {"name":"1000","properties ...

Angular 5 - capturing form inputs - activating event upon selecting suggested values

When I click on suggested values below the input field, the (click)="doSomething()" event doesn't fire. How do I handle this issue? I would like to be able to type something in the input field and then have an event triggered when clicking on the su ...

Exclude the initial argument from functions listed within a JSON structure

Is there a way to create a generic type that reflects a JSON object structure, but excludes the first argument from functions while maintaining the types of other arguments? type InputType<T> = { increment: (state: T) => T, add: (state: T, cou ...

React-bootstrap-table Axios delete operation causing [object%20Object] to be displayed in the browser console

I am having trouble executing a delete operation using axios on a react-bootstrap-table, and encountering this error in the console DELETE http://localhost:9000/api/terminals/[object%20Object] Uncaught (in promise) Error: Request failed with status cod ...

Yes, it's not able to retrieve the value from headlessui combobox

I have encountered an issue while using the Headlessui combobox component in conjunction with Yup. Despite successfully storing the selected value in the selectedMemory state variable, Yup consistently generates a required error message. I seem to be overl ...

Mastering mapped types to replace properties in Typescript

I have created a Factory function where it takes an object as input and if that object contains specific properties, the factory transforms those properties into methods. How can I utilize mapped Types to accurately represent the type of the resulting obj ...

"Utilizing Postgresql with TypeORM for filtering many-to-many relationships

I have two entities that are connected with a ManyToMany relationship: // Branch entity @ManyToMany( (type) => User, (e) => e.branches ) users: User[]; // User entity @ManyToMany( (type) => Branch, (e) ...

Issue with applying the React Material UI ThemeProvider

I'm having issues with applying styles using @material-ui/core in my React app. Some of the styles are not being applied properly. You can check out my sandbox for the full code (relevant snippets below). Although I followed the instructions from Ma ...