Tips on utilizing the i18n t function within a TypeScript-powered Vue3 component

I am working on creating a control that can automatically manage interpolation for internationalization (i18n) strings:

<script lang="ts">

import { ref, defineComponent, inject } from "vue";
import type { InterpolationItem, InterpolationData, myData } from "../types/types";
import { useI18n } from 'vue-i18n'
    
export default defineComponent({
  name: "LocCtrl",
  props: {
    locKey: {
      type: String,
      required: true,
    },
    page: {
      type: String,
      required: true,
    },
  },
  setup() {
    // The necessary steps with useI18n() should be implemented here. If placed at the top, the compiler
    // prompts it to be placed here instead, but where exactly?
    const { rt, t } = useI18n();

    const myData = inject("myData") as myData;
    const data = ref<InterpolationData>({
      items: [],
    });

    return {
      data,
      myData
    };
  },
  mounted() {
    // At the moment, t (or whatever is needed) remains undefined
    this.data.items = this.performInterpolation( t(this.page + "." + this.locKey));
  },

The queries regarding my objective are highlighted in the comments above

Answer №1

My setup encountered several issues that needed to be addressed. The following project provides a template that can be cloned and used to transfer configurations into your own project, such as with Beyond Compare. It may be necessary to utilize the package.json settings mentioned in the linked issue for successful npm installation.

Link to GitHub Issue

I faced challenges with my makeshift Locale.ts file potentially causing interference with the functionality of i18n. Removing it completely resolved the i18n operation.

Upon correct installation, both this.$t and this.$i18n are accessible within components throughout the project.

mounted() {
    // an illustration of changing the locale, not mandatory every time:
    const storage = useLocalStorage("site_locale", "en-US");
    this.$i18n.locale = storage.value;

    // invoking custom interpolation code
    this.data.items = 
      this.interpolate(this.getItem(this.page, this.locKey));
  },
  methods: {
    // functions directly accessing i18n strings:
    getItem(page: string, key: string): string {
      return this.getLoc(page + "." + key);
    },
    getLoc(x: string): string {
      return this.$t(x);
    },

Once i18n is functional, this demonstration utilizes yaml as the loc file format. Utilizing a yaml beautifier tool like the one provided helps identify formatting errors that might otherwise cause uninformative loading errors:

YAML Beautifier Tool

Certain lines necessitate quotation marks if they contain specific characters like colons, brackets, or @:lookupSomething.something references:

xBox:
  NC: "@:common.NC"
  CP: Change X
  PE: Pre-existing Conditions
  xDesc: "[petData^xAge] [*ageUnit**xData^ageUnit] old [xData^breed]"
  SO: Start Over
  WP: Wrong X?

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

Error message thrown when attempting to access Navigator InjectionToken in tests: ReferenceError - Navigator is not defined

I have created an abstraction for the Navigator object: export const NAVIGATOR: InjectionToken<Navigator> = new InjectionToken<Navigator>( 'An abstraction over window.navigator object', { factory: () => inject(WINDOW).navig ...

Exporting enums within types in React Typescript

Here are the files I have: VehicleBrands.ts: export enum VehicleBrands { FORD = "ford", HONDA = "honda" } VehicleBrand.ts: import {VehicleBrands} from "./VehicleBrands"; export type VehicleBrand = VehicleBrands.FORD | V ...

How can I integrate React-Router Link as a component within Material-UI using Typescript?

Hey everyone, I've encountered an issue while trying to utilize Material UI's component prop to replace the base HTML element of a component. Error: The error message reads: Type 'Props' is not generic. This problem arises from the fo ...

Is it possible to view the list of errors displayed by vscode when opening a JS file exclusively through the terminal?

Is there a default configuration file that vscode uses to display errors and warnings? I want to identify all issues in my JavaScript project. I don't have any jsconfig.json or tsconfig.json files, only using the //@ts-check directive in some files. ...

Manipulating CSS Class Properties Using JavaScript

In my JavaScript application, there is a functionality that loads a list of items for users to click and view detailed information in a separate div on the page. Users should be able to interact with and make modifications to these individual item overview ...

Angular - failure to detect function execution by spy

I've been trying to test a feature module, but I'm facing some difficulties. The last test is failing because the spy isn't detecting that the method is being called, even when I move the this.translate.use(this.currentLanguage.i18n) call ou ...

Steps to add annotations to a class descriptor:

Can you help me with the correct way to annotate this piece of code? export class TestCls { static SomeStaticFn(): TestCls { // Do some stuff... // Return the class descriptor for a "fluid usage" of SomeStaticFn return TestCls ...

Determine the data type of the value for the mapped type

Is there a way to access the value of a type like the following: interface ParsedQs { [key: string]: undefined | string | string[] | ParsedQs | ParsedQs[] } I am looking for a method to retrieve the ParsedQsValue type without directly duplicating it from ...

Angular 2 Unit test issue: Unable to resolve parameters for 'RequestOptions' class

I am currently working on testing a simple component that has some dependencies. One of the requirements is to provide certain providers for the test. /* tslint:disable:no-unused-variable */ import { By } from '@angular/platform-browser&ap ...

An issue has been identified with React's HTML input maxLength feature where it does not display an error

Within my form, I have an input field that currently does not include validation for a maximum length. <input type="text" className="form-control" id="company" onBlur= ...

Sending JSON object data to an API endpoint using the POST method in an Angular application

Attempted to post data to an API, but received a 400 bad request error. After testing with Postman, it seems that the issue may lie within my service or TypeScript code. As a newcomer to Angular, I am seeking assistance as I have searched extensively witho ...

Error encountered while attempting to resume activity: TypeError - the function `callResume` is not defined in NativeScript Angular 2

When the resume event occurs, I must invoke the method this.callResume(). However, upon calling the method, a runtime error is thrown: TypeError: this.callResume is not a function I am uncertain about how to call a method from within the resume method ...

Adding a static global constant in webpack dynamically

I'm facing a challenge with adding a global constant to my project using webpack.DefinePlugin. I've successfully added one in the module.exports, but I struggle to do this conditionally. When I declare and use '__VERSION__' in my module ...

Node.js: Managing multiple occurrences of the same event name for testing purposes

When it comes to unit testing using mocha, I am looking for a way to set up an asynchronous queue for handling events. Previously, I used a once() Promise to wait for events like this: import EventEmitter from 'events' import { once } from ' ...

Transforming a detailed JSON structure into a more simplified format with Angular 2

As a newcomer to Angular 2, I find myself encountering a hurdle in filtering unnecessary data from a JSON object that is retrieved from a REST API. Below is an example of the JSON data I am working with: { "refDataId":{ "rdk":1, "refDataTy ...

Develop a series of sequential tests for the playwright to execute

Can someone assist me with my code? I am attempting to write a test in Playwright that navigates to the forgot password page, creates a new password, and then tries to log in using that new password. However, I am encountering an issue with retrieving the ...

Despite setting the esModuleInterop flag, I am still encountering an error with default imports

My React project with TypeScript is causing some issues. In the main tsx file, the import React from 'react' line works fine. However, in my test file, I keep getting the TS1259 error. I suspect there might be a problem with my TS/Jest/Babel conf ...

Sporadic UnhandledPromiseRejectionWarning surfacing while utilizing sinon

Upon inspection, it appears that the objects failApiClient and explicitFailApiClient should be of the same type. When logging them, they seem to have identical outputs: console.log(failApiClient) // { getObjects: [Function: getObjects] } console.log(expli ...

How to perform a fetch on a local path in Next.js?

Is there a way to use the fetch method with a relative path like this: export async function getServerSideProps() { // Fetch data from local API const res = await fetch(`/api/get_all_prices`) const data = await res.json() // Pass data to th ...

The incredible power of the MongoDB $inc field

I am facing a challenge in writing a function that accepts a record id, an action (inc or dec), and a field name as a string to be incremented (can be 'likes', 'subs' or any other). The issue is that I am unable to find a way to replac ...