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

The error message "Property '...' is not found on the type 'ServerContextJSONValue'" pops up whenever I try to utilize the useContext() function

After creating a Provider and defining the type, I encountered a TypeScript error when using it with useContext(): "Property '...' does not exist on type 'ServerContextJSONValue'. I'm not sure what I am missing. Can anyone help me ...

PlayWright - Extracting the text from the <dd> element within a <div> container

Here is the structure I am working with: <div class="aClassName"> <dl> <dt>Employee Name</dt> <dd data-testid="employee1">Sam</dd> </dl> </div> I am attempting to retrie ...

Obtain merged types by accessing a particular property within a deeply nested object

My query is reminiscent of a post on Stack Overflow titled Get all value types of a double-nested object in TypeScript However, my specific requirement involves extracting union types from the values of a designated property. const tabsEnum = { IDCardRe ...

What could be the reason my component is not displaying the ContentChild associated with a directive?

It appears that utilizing a directive to target a content child from another directive is the recommended approach (source). However, why isn't my component able to recognize the component marked with the directive? ./my.component.ts import { Comp ...

Exploring TypeScript Module Importation and WebPack Integration

Struggling with WebPack's injection of imported dependencies for a TypeScript project. The first challenge is getting TypeScript to recognize the imported module. In the header.ts file, there is a declaration of a module nested under vi.input, export ...

Integrating one service into another allows for seamless access to the imported service's properties and methods within an Angular

After reviewing the content at https://angular.io/guide/dependency-injection-in-action, it appears that what I am trying to achieve should be feasible. However, I encounter this error when attempting to invoke a method on my injected service from another s ...

The array does not yield any values when utilizing Angular CLI

Recently, I created a component that contains an array of strings. Here's the code snippet for reference: import {Component} from '@angular/core'; @Component({ selector: 'app-products-list', templateUrl: './products-list. ...

What are the steps to integrate material-ui with styled-components effectively?

import styled from "styled-components"; import Button from "@material-ui/core/Button"; export const StyledButton = styled(Button)` margin: 20px; `; I'm having trouble adjusting the button styling. How can I add a margin to the ...

ESLint detected a promise being returned in a function argument where a void return type was expected

I'm encountering a recurring error whenever I run my ESLint script on multiple routers in my server. The specific error message is as follows: error Promise returned in function argument where a void return was expected @typescript-eslint/no-misuse ...

Exploring Vue 3 and Accessing Objects in Arrays

I need help generating passwords reactively using an array object inside my instance. I am able to list this object with v-for and generate random passwords with characters in a passArry. However, I am struggling to send chars in data to the passArray wh ...

What is the correct way to declare a variable with a generic type parameter?

Exploring the following code snippet that showcases a React component being defined with a type argument named TRow: function DataTable<TRow> ({ rows: TRow[] }) { return ( ) } Prior to this implementation, ES6 was utilized and components were c ...

Is it possible to modify the CSS styling in React using the following demonstration?

I am attempting to create an interactive feature where a ball moves to the location where the mouse is clicked. Although the X and Y coordinates are being logged successfully, the ball itself is not moving. Can anyone help me identify what I might be overl ...

Issue with Symbol Constructor in Typescript: [ts] The 'new' keyword can only be used with a void function

Just starting out with typescript and experimenting with the ES6 Symbol constructor. How can I address this ts lint problem without resorting to using any? const symbol = new Symbol(path); I'm trying to avoid doing this: const symbo ...

Retrieve a collection of Firestore documents based on an array of unique identifiers

I have a Firestore collection where one of the values is an array of document IDs. My goal is to retrieve all items in the collection as well as all documents stored within the array of IDs. Here is the structure of my collection: This is my code: export ...

Encountering a type mismatch error in Typescript while working with Redux state in a store file

It appears that I have correctly identified all the types, but could there be a different type of Reducer missing? 'IinitialAssetsState' is not assignable to type 'Reducer' The complete error message: Type '(state: { assets: n ...

Tips for patiently anticipating the completed response within an interceptor

Using the interceptor, I want to display a loading spinner while waiting for subscriptions to complete. This approach works well in individual components by showing and hiding the spinner accordingly: ngOnInit() { this.spinnerService.show(); this. ...

Is there a way to utilize a nearby directory as a dependency for a separate Typescript project?

I am working with a repository that has the following structure in typescript: . ├── common ├── project_1 └── project_2 My goal is to have the common package be used by both project_1 and project_2 as a local dependency. I am looking for ...

The Conundrum of Angular 5 Circular Dependencies

I've been working on a project that involves circular dependencies between its models. After reading through this StackOverflow post and its suggested solutions, I realized that my scenario might not fit into the category of mixed concerns often assoc ...

Challenges faced while addressing angular package.json dependencies for a live build

For several hours now, I've been struggling to make npm run build:production work. This command is included as part of my build process when a branch is pushed. However, I have encountered an issue with my package.json file that I haven't been ab ...

The juvenile entity does not align with the foundational entity [typescript]

After setting "strict": true in my tsconfig.json, I encountered compiler errors when attempting to run the code. To replicate and explore this issue further, you can try running the following code snippet. The problem arises when the child clas ...