A guide to implementing vue-i18n in Vue class components

Take a look at this code snippet:

import Vue from 'vue'
import Component from 'vue-class-component'

@Component
export default class SomeComponent extends Vue {
  public someText = this.$t('some.key')
}

An error is being thrown:

[Vue warn]: Error in data(): "TypeError: i18n is undefined"

I have made sure to initialize Vue with Vue.use(VueI18n) and new Vue({ /* ... */, i18n }). The initialization of the i18n object looks like this:

new VueI18n({
  locale: DEFAULT_LOCALE, // imported
  fallbackLocale: 'en',
  messages // imported
})

Translations seem to be working fine unless they are immediately called, such as in templates or component methods.

This particular issue regarding vue-i18n suggests that there might be an initialization problem.
A workaround could involve utilizing methods and translating only within templates. Nevertheless, there are instances where immediate calls cannot be avoided, for instance when dealing with Vuetify input rules.

someRule = [(v) => !!v || this.$t('field.must_not_be_empty')]

These rules are triggered instantly, even with lazy-validation activated on Vuetify forms.

I have identified two potential solutions:

  1. Finding a way to bypass the Vuetify rules system and directly include a string for translation in the template;
  2. Solving the immediate availability issue of $t.

However, I have not been successful in implementing either option.

Is there any known solution to tackle this issue?

Answer №1

The issue arose from the improper utilization of the keyword this.
Essentially, Vue requires a highly specific execution context that differs from what is typically available in the main context of a new class.

The remedy turns out to be straightforward: Implement a getter.

import Vue from 'vue'
import Component from 'vue-class-component'

@Component
export default class SomeComponent extends Vue {
  public get someText () { return this.$t('some.key') }
}

Answer №2

The solution of placing the error message in a getter did not resolve my issue within the Vuetify input rules setup. I encountered the following error:

Error in beforeMount hook: "TypeError: Cannot read property '_t' of undefined"

I found two alternative ways to make it work:

  1. Utilizing a getter for the entire rules array:
get someRules() {
    return [
        (v) => !!v || this.$t('field.must_not_be_empty')
    ];
}
  1. Including the rules within the @Component decorator:
@Component({
    data() {
        return {
            someRules: [
                (v) => !!v || this.$t('field.must_not_be_empty')
            ]
        };
    }
})
export default class SomeComponent extends Vue {
...
}

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

I need to explicitly tell TypeScript that there are optional numeric properties on two objects that need to be compared

I am faced with the challenge of sorting an array of objects based on an optional integer property called order, which falls within the range of [0, n]. To achieve this task, I am utilizing JavaScript's Array.prototype.sort() method. Given that the p ...

VS Code is having trouble understanding the Vue 3 linting

My experience with Vue 2 and VS Code was fantastic, but upon switching to Vue 3 and Velur, I have encountered some unexpected issues: https://i.sstatic.net/hMibN.png Although the component VoteBtn is imported and utilized in the code above, the linter is ...

Repeated keys found within a component's v-for loop

Dealing with v-for Duplicate Keys Error Even though the list is returned successfully, there seems to be a problem when I update a user in the array by changing their role. An error about duplicate keys is triggered. The key is assigned using the user&apo ...

Having trouble with Axios cross-origin POST request CORS error in React / Typescript, even after trying all the common solutions

I am encountering a CORS error in my React / Typescript project when trying to make a POST request using Axios. The project uses a Node.js / Express backend. Despite researching common CORS errors and reading highly-rated posts on the topic, I have been un ...

Issues arise in Ionic 3 when attempting to use scripts or external custom jQuery plugins within inner pages

When I utilize a script tag in my index.HTML file, it functions properly on the initial or root pages of Ionic 3. However, upon navigating to other pages using NavController, the script ceases to work on these inner pages. How can I implement a custom jQ ...

Can someone please share a straightforward method for dynamically rendering views in Vue.js?

Let's pause and consider the scenario: You're creating a modular interface, where any module that implements it must be able to 'render itself' into the application using a slot and state. How can you achieve this in Vue? An Example S ...

Error: Type '() => () => Promise<void>' is not compatible with type 'EffectCallback'

Here is the code that I'm currently working with: useEffect(() => { document.querySelector('body').style['background-color'] = 'rgba(173, 232, 244,0.2)'; window.$crisp.push(['do', 'ch ...

Unexpected security question arising from vue-CLI output

As I work on my Vue.js application, I've encountered a sudden issue with vue-cli producing error messages that raise concerns about potential malicious dependencies. Executing npm run serve (vue-cli serve) appears to be successful, but it generates m ...

Implementing conditional asynchronous function call with identical arguments in a Typescript React project

Is there a way in React to make multiple asynchronous calls with the same parameters based on different conditions? Here's an example of what I'm trying to do: const getNewContent = (payload: any) => { (currentOption === myMediaEnum.T ...

Unclear value of button when being passed

In my Welcome.html file, I am attempting to send the value of a button to a function that simply logs that value. This function is located in a functions class that has been imported into my welcome.ts file. <ion-content padding id="page1"> <h1 ...

What could be causing the malfunction of the Bootstrap5 modal hide feature?

Today, I am facing an issue with hiding the Bootstrap5 modal in a TypeScript function. Despite trying to invoke the hide function on the modal element, it does not work as expected. Here is the minimal code snippet to reproduce this problem: import React f ...

Tips for building a versatile client-server application with separate codebases for the JavaScript components

We are embarking on the process of rebuilding our CMS and leveraging our expertise with VueJS. Despite our familiarity with VueJS, we won't be able to create a full single-page application due to the presence of server-side rendering files (JSP). The ...

In AngularJS, the use of the '+' operator is causing concatenation instead of addition

Looking for assistance with my TypeScript code where I've created a basic calculator. Everything is working as expected except for addition, which seems to be concatenating the numbers instead of adding them together. HTML CODE : <input type="tex ...

Troubleshooting issue with absolute paths in Vite project using React and TypeScript

I'm having trouble implementing absolute paths in a Vite react-ts project. This is how I set up the project: npm init @vitejs/app npx: installed 6 in 1.883s √ Project name: ... test-vite √ Select a framework: » react √ Select a variant: » rea ...

Send an API request to update a table in a Vue.js application

I am currently learning about VUE and have a simple API request that provides information on bitcoin prices. I would like to update the table every second and am seeking the easiest way to achieve this. Below is the code snippet: async mounted() { const re ...

Exploring Nuxt's Getters with vuex-class for seamless data retrieval

Currently, I am in the process of developing an application using Nuxt and experimenting with vuex for the first time. Despite following numerous tutorials to set it up, I'm encountering difficulties accessing the store and suspect that the issues may ...

Exiting a void method in JavaScript/Typescript using the return or break statement

I find myself dealing with a complex method in Typescript that contains multiple if else if else constructs. It's a void method, and I'm wondering how I can exit the method based on a specific if condition without having to execute the remaining ...

What is the process for extracting the paths of component files from an Angular ngModule file?

I've been on the lookout for automation options to streamline the process of refactoring an Angular application, as doing it manually can be quite tedious. We're working on reducing our app's shared module by extracting components/directive ...

Specialized typescript function that is compatible with extended interfaces

Is there a way to create a versatile function that can be applied to any interface derived from a top-level interface? This function should take an unpersisted interface (without an id property) and return a persisted one (with an id property). The two ma ...

Can you use `keyof` to create a template literal type?

Defined a form schema type example: type FormSchema = { username: string; settings: { theme: string; language: string } } Now, trying to define the Form Input type like this: type FormInput = { id: keyof FormSchema | `${keyof FormSchema}.${string}` } Enc ...