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

Sharing an object's attributes as props in Vuejs

Greetings everyone, I am facing some confusion. I am working with two components (child and parent component) where I pass the properties of an object as props <child :child-data="abc" ></child> Vue.componen ...

What is the best way to scan through Vue and React component-based web applications?

I am facing an issue when trying to crawl my Single Page Application (SPA) created with the Vue framework, which is similar to React. Despite my efforts, the content does not appear to be rendered during the crawling process. Here is the result I am gettin ...

Hydration has finished, but there are some discrepancies - Utilizing Ascii art within a vue component

I encountered an issue with displaying ascii art in the {{ name }} section of my component. While developing, a Vue warning popped up: Hydration text content mismatch in <pre> Followed by an error message: Hydration completed but contains mismatch ...

What is the best way to conceal a paragraph with v-if within the context of Vuex?

I have been working on a small app that involves clicking a button to hide a paragraph, but I am using vuex for implementation purposes. The Home.vue file contains the paragraph and the About.vue file has the button. I want the paragraph to disappear bas ...

Can someone please point me in the right direction to locate a Typescript project within Visual Studio

I've been struggling with this issue for days and still can't find a solution. After installing the Typescript tool for Visual Studio 2015, it appears to be successfully installed. https://i.stack.imgur.com/nlcyC.jpg However, I am unable to loc ...

Array filtering functions similarly to marketplace filtering tools

In order to make the filter function like a marketplace filter, I want to only see items related to the selected brand and status. For example: partners = [ 0:{ year: "2022" badge_status: "badge-success" sale_date: "01/07/2022&quo ...

When accessing nested objects in Props in Vue.js, an error may occur if the property of null/undefined

When I make an axios call, I receive an object which I pass to a child component. However, when I attempt to loop through the object in the child component to access a property of another nested object, I encounter an issue where the property is showing as ...

Encountering an error when trying to insert a row in Laravel 5 with a foreign

While attempting to add a new record to the database in Laravel, an error was returned: "message": "SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'usu_idrol' cannot be null (SQL: insert into usuarios (cedula, nombre, tele1, tele2, ...

Steps for sorting items from a list within the past 12 hours

I'm currently working with Angular and I have data in JSON format. My goal is to filter out items from the last 12 hours based on the "LastSeen" field of the data starting from the current date and time. This is a snippet of my data: { "Prod ...

The Application Insights Javascript trackException function is giving an error message that states: "Method Failed: 'Unknown'"

I've been testing out AppInsights and implementing the code below: (Encountering a 500 error on fetch) private callMethod(): void { this._callMethodInternal(); } private async _callMethodInternal(): Promise<void> { try { await fetch("h ...

When using Vue with CSS3, placing an absolute positioned element within a relative wrapper can cause issues with maintaining the

Just starting out with Vue and diving into the world of CSS3! I'm currently working on a component that you can check out here: https://codesandbox.io/s/yjp674ppxj In essence, I have a ul element with relative positioning, followed by a series of di ...

What is the best way to remove Vuetify and Vue from the build process?

I am developing a custom library using VueCLI and I am looking to optimize the size of the build by excluding vuetify and vue.js from the final bundle. Currently, my final build file (*.umd.min.js) is functioning correctly with the following command: vue ...

Angular Error: Unable to access properties of null (specifically 'validators')

I am encountering an issue with my Angular code where I receive the error message "TypeError: Cannot read properties of null (reading '_rawValidators')". import { Component, OnInit } from '@angular/core'; import { Wifi } from './wi ...

How to activate a button only if the specified conditions are met using VueJS 3

I'm currently facing challenges while working on a form to enable a button when certain conditions are met. The form I created includes fields for name, phone number, options, and a message. Once all requirements are filled, I aim to re-enable the di ...

Enhance the MUI palette by incorporating TypeScript, allowing for seamless indexing through the palette

When utilizing the Material UI Palette with Typescript, I am encountering a significant issue due to limited documentation on MUI v5.0 in this area. Deep understanding of typescript is also required. The objective is to iterate through the palette and vir ...

Having trouble resolving errors in Visual Studio Code after failing to properly close a parent function? Learn how to fix this issue

Here we have the code starting with the construct function followed by the parents function public construct() //child { super.construct; } protected construct() //parent { } The issue arises where I am not receiving an er ...

Tips for utilizing global functions in VUE 2 CLI crowd

I have multiple components that require the same functions. Is there a way to avoid duplicating the code in each component and instead use it globally...? Even if I put the function in the App.vue, it still isn't accessible in the components. ...

How to retrieve a value from a base64-decoded string in Angular 6?

I successfully decoded a Base64 string using the xml2js library and obtained the following XML value: <?xml version="1.0" encoding="UTF-8" standalone="no"?> <svg width="293" height="102" viewBox="0 0 293 102" xmlns="http://www.w3.org/2000/svg" ...

Having trouble accessing props from the Vue root within a component template - any ideas why?

I am currently facing an issue while trying to retrieve job_execs from the stage-execs component within the template... The job_execs variable is initialized in the main Vue instance, and I am attempting to pass it as a prop to the stage-execs component. ...

Update individual component based on selected value

I am working on a blogs page that consists of two main components: filter and card <template> <div> <div v-if='$apollo.loading'>Fetching data...</div> <div v-else> <FilterComponent :categorie ...