Having trouble with Vue i18n and TypeScript: "The '$t' property is not recognized on the 'VueConstructor' type." Any suggestions on how to resolve this issue?

Within my project, some common functions are stored in separate .ts files. Is there a way to incorporate i18n in these cases?

// for i18n
import  Vue  from 'vue'
declare module 'vue/types/vue' {
  interface VueConstructor  {
    $t: any
  }
}
declare module 'vue/types/options' {
  interface ComponentOptions<V extends Vue> {
    t?: any
  }
}

(() => {
  const test = Vue.$t('auth.title');
  console.log( test )
})()

An error is returned:

Property '$t' does not exist on type 'VueConstructor<Vue>"

How can this be resolved?

Answer №1

To achieve the same outcome, follow these steps:

Step 1: Create a separate index.ts file within an i18n folder (you can choose the root level or any other location in your app)

i18n/index.ts

import Vue from 'vue';
import VueI18n from 'vue-i18n';

// Register the i18n module
Vue.use(VueI18n);

const i18n = new VueI18n({
   locale: 'nb-NO', // Use "window.navigator.language" to get the browser language
   fallbackLocale: 'en',
   messages: {en, no},
   silentTranslationWarn: true
})

const translate = (key: string) => {
  if (!key) {
    return '';
  }
  return i18n.t(key);
};

export { i18n, translate}; // Export the above method

Step 2: Ensure that you use(import) the code above in main.ts

main.ts

import { i18n } from '@/i18n';

new Vue({ i18n, render: h => h(app) }).$mount('#app')

After configuring the above steps, you will be able to use translations anywhere in your application.

Step 3: How to use it in .ts and .vue files

// First import it into the file
import { translate, i18n } from '@/i18n';

// This is how we can use translation inside HTML templates
<template>
  <h1>{{'sample text' | translate}}</h1>
</template>

// This is how we can use translation inside .ts or .vue files
<script lang='ts'>    
  // Normal scenario
  testFunc(){
    let test = `${translate('sample text')}`;
    console.log(test );
  }

  // In your case, it should be like this:
  (()=>{
    const test = `${translate('auth.title')}`;
    console.log(test)
  })()
</script>

I trust that these guidelines will assist you in resolving your issue.

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

Click to shift the div downwards

Currently, I have a piece of javascript applied to a div that directs the user to a specific link: <div style="cursor:pointer;" onclick="location.href='http://www.test.com';"> I am wondering if there is a way to add an effect where, upon ...

Creating a cutting-edge mobile application using PhoneGap and Node.js

I have a vision to develop an app similar to a mobile messenger, but I am not a seasoned programmer. My knowledge of JavaScript is at an intermediate level, although I haven't utilized it for any significant projects. The main focus of the app would i ...

Utilize the Material UI feature to call the function

How can I pass a function as a prop to my Material UI component if the function is undefined within the component? import React, { Component } from 'react'; import styled from 'styled-components'; import InputBase from '@material- ...

Utilizing Angular's ng-Grid with Promises

My current setup involves fetching a JSON file through a service to serve as the data source for my grid. The service successfully fetches the data, and the grid renders its basic layout correctly. However, there seems to be an issue with populating the gr ...

Display intricate header and preview in a printed datatable

Hey there, I've been using the Datatable plugin and it's really great. However, I've come across a problem with complex headers like this: <thead> <tr><td>some text</td></tr> <tr><td>some te ...

What is the best way to implement ternary operators in a text input field using vue.js 2?

My Vue component looks like this: <template> <div> ... <li v-for="category in categories"> ... <input type="radio" class="category-radio" :value="category.id" (category.id == ...

What is the best way to eliminate leading zeros in PHP when echoing SQL statements?

Being a front-end programmer on a team of three, my PHP/MySQL skills are fairly basic. However, our back-end programmer is going on vacation and we have a deadline to address a minor visual detail. Currently, we are working on a page that displays multiple ...

Is there a way to reverse the hover effect on div elements?

Let's start by examining the code I've written: HTML: <div class="button_container"> <div class="inner_button"> <a href="#" class="button_text">Button</a> </div> <div class="button_side"> ...

Tips for organizing Protractor promises

I am currently experimenting with determining if an element is positioned at the bottom of a page in Protractor/Webdriver using promises. However, I feel like my current approach is quite messy and there must be a cleaner way to achieve this. describe(&ap ...

Displaying adornments in a vertical arrangement within a TextField using Material UI

Is there a way to display adornments vertically in a Material UI Textfield? I've been trying but it always shows up horizontally. Snippet: <TextField variant="filled" fullWidth multiline rowsMax={7} onFocus={() => h ...

Simple Bootstrap Input Slider Configuration

I am attempting to create a simple setup for a bootstrap-style input slider, but I am facing some difficulties getting it to function properly. Desired Outcome: https://i.sstatic.net/Btfo3.png Actual Outcome: https://i.sstatic.net/0VnNv.png Resource / ...

Pausing in a NodeJS HTTP request listener until receiving another response before proceeding

Essentially, this is a web proxy. Within a request listener, I am creating another http request, reading its response, and passing it to the main response. But I have the challenge of needing to wait for the secondary request to complete before continuing. ...

Is There a Way to Abandon a route and Exit in Express during a single request?

In order to ensure proper access control for the application I was developing, I structured my routing system to cascade down based on user permissions. While this approach made sense from a logical standpoint, I encountered difficulties in implementing it ...

Is it simple to host a vue.js web application within the assets folder of a sails.js project?

Currently, I am in the process of learning how to utilize Sails.js and vue.js. My goal is to develop a small application where a vue.js application is situated within the assets/ directory of Sails.js. The challenge I'm facing is figuring out how to s ...

successive ajax requests

I am facing a challenge where I need to execute two separate ajax calls sequentially. The second call relies on the result of the first call for its data. Despite my efforts, I haven't been able to achieve the desired outcome. Here's what I have ...

Is there a way to customize the default MuiCheckbox icon in theme.ts?

How can I customize the icon default prop for Mui checkbox? I followed the instructions provided here and used a snippet from the documentation: const BpIcon = styled('span')(({ theme }) => ({ borderRadius: 3, width: 16, height: 16, .. ...

How can I retrieve information from SafeSubscriber?

I need to develop an Angular application that fetches data from the backend and displays it on the front end, along with some predefined hard-coded data. The communication in my project happens between two files: client.service.ts import { Injectable } f ...

The standard date format used in Javascript/Jquery programs

I have a kendo date picker set to display dates in the format "MM/dd/yyyy". I need to use jquery or javascript to ensure that the selected date is not in the future and is greater than '01/01/1900'. The problem I'm encountering is handling ...

Struggling to retrieve the 'this' object using a dynamic string

Within my Nuxt + TS App, I have a method that attempts to call a function: nextPage(paginationName: string): void { this[`${paginationName}Data`].pagination .nextPage() .then((newPage: number) => { this.getData(pagination ...

Guide on how to trigger loader page during execution of Selenium code in Python

I am currently developing a Python Flask web application that incorporates Selenium in the backend. One of my objectives is to disable the webpage when the Selenium driver is running to prevent user interference. Below is the code snippet I am using: < ...