The Vue-i18n global method this.$t is not functioning within a function

Global vue-I18n Definition:

Vue.use(VueI18n);
export default new VueI18n({
  locale: process.env.VUE_APP_I18N_LOCALE || 'cs',
  fallbackLocale: process.env.VUE_APP_I18N_FALLBACK_LOCALE || 'cs',
  messages: loadLocaleMessages(),
});

The usage is widespread:

this.$t('sign-up.something-went-wrong')

However, it cannot be used within a for each loop due to the creation of a new anonymous class. How can it be referenced from there?

function convertErrors(jsonErrors) {
  const veeErrors = {};
  console.log(this.$t('sign-up.heading'));
  return veeErrors;
}

Also to be called from export.default

methods: {
  async submitForm() {
    try {
      const { data } = await this.$store.dispatch('CREATE_USER_PROFILE', {
        email: this.email,
        password: this.password,
        nickname: this.nickname,
      });

      if (!this.personalData) {
        this.success = true;
        return true;
      }

      if (data.token === undefined) {
        this.error = this.$t('sign-up.something-went-wrong');
        return false;
      }

      const jwtData = jwtDecode(data.token);
      const vehicles = [];
      setVehicles.call(this, vehicles);
      await this.$store.dispatch('UPDATE_USER_PROFILE', {
        jwt: data,
        userId: jwtData.userId,
      });
      this.success = true;
    } catch (error) {
      this.success = false;
      if (error.response) {
        console.log(this.$t('sign-up.something-went-wrong')); // this works
        const veeErrors = convertErrors(error.response.data); // this fails
        this.$refs.form.setErrors(veeErrors);
      } else {
        this.error = this.$t('sign-up.something-went-wrong');
      }
    }
    return this.success;
  },
},

An error message in chrome console reads:

vue.runtime.esm.js?2b0e:619 [Vue warn]: Error in v-on handler (Promise/async): "TypeError: Cannot read property '$t' of undefined"

Additionally,

TypeError: Cannot read property '$t' of undefined
at convertErrors (SignUpForm.vue?9fa9:236)
at VueComponent._callee$ (SignUpForm.vue?9fa9:321)
at tryCatch (runtime.js?96cf:45)

Answer №1

convertErrors does not have access to "this" because it is not bound to a component. To solve this issue, you need to move it into the component's methods so that you can reference this:

methods: {
  convertErrors(jsonErrors) {
    const veeErrors = {};
    console.log(this.$t('sign-up.heading'));
    return veeErrors;
  }
}

Alternatively, you can use call to set the context (the this) inside convertErrors:

const veeErrors = convertErrors.call(this, error.response.data);

Answer №2

Before going through each item in the VueComponent, you can save it to a variable like shown below:

let self = this
// .......
jsonErrors.errors.forEach((error) => {
  if (error.field) {
    veeErrors.$field = [self.$t(error.messageKey)];
  } else {
    self.error = self.$t(error.messageKey);
  }
});

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

Discover real-time results of accordions and their information as you search

I am looking to add a search functionality to filter through a list of accordions and their contents on my HTML page. I want the search box to be able to search both the accordion titles and the content within each accordion. This is my first time posting ...

Tips on how to implement asynchronous AJAX calls in Marionette JavaScript

When a button is clicked in my front-end JavaScript app, I make an AJAX call to send data to the back-end using the following code: submit: function(e){ e.preventDefault(); var formData = $('form').serializeArray().reduce(function(a, x) ...

Issue with applying projection to graticule in D3 and Three.js: unable to execute projection on graticule

My current project involves creating 3D graticules using three.js. The process starts by constructing a mollweide projection graticule in SVG with D3, followed by extracting the graticule path points and converting them to three.js vectors. However, the r ...

What is the best way to utilize mapping and filtering distinct values in an array using TypeScript?

What is the best way to filter and map distinct elements from an array into another array? I've experimented with various methods but keep encountering a syntax error stating "Illegal return statement". My objective is to display only unique items f ...

Error: Identical div IDs detected

<div id="tagTree1" class="span-6 border" style='width:280px;height:400px;overflow:auto;float:left;margin:10px; '> <a class="tabheader" style="font-size:large">Data Type</a><br /> <div class="pane">Refine sea ...

Nested tables with repeated data using AngularJS' ng-repeat functionality

As a newcomer to angularjs and web-development, I am facing a challenge with using ng-repeat to display data in a complex table structure, like this: A B C D abc pqr xyz std Here is the code snippet: <div class="table-responsive"> ...

Having trouble disabling JavaScript with Selenium

I'm attempting to disable JavaScript through the Selenium profile when launching a browser. This method has worked in the past, but after updating my Selenium/Firefox versions, I am encountering difficulties. profile = webdriver.FirefoxProfile() ...

Dealing with browser timeouts for HTTP requests using JavaScript

Managing time out situations in a web application when calling a REST API is crucial. Below is the code snippet I am using to make the API call with jQuery ajax. $.ajax({ type: "POST", url: endpoint, data: payload, ...

"Sending the real object as a parameter to a function when triggering an event

Whenever I click a button, I want to pass the 'contract' object into it. <td class="col-md-1" colspan="1" style="text-align: center; vertical-align: middle;"> <button class="btn btn-primary" data-ng-click="removeContract(ctrl.select ...

Matching wildcard paths using Express

Seeking help with routing in Express. I am trying to have both /m/objectID and /m/someslug/ObjectID directed to the same function. My current setup is as follows: app.get("/m/:id", ...); app.get("/m/(.*)/:id", ...); The first route is working properly, b ...

Having trouble uploading a file to Node JS

After commenting out the app.use(fileUpload) line, I noticed that the breakpoint set on app.post is triggered from the browser. However, an error occurs stating Exception has occurred: TypeError: Cannot read property 'filetoupload' of undefined ...

Error 19: Constraint violation - duplicate entry detected

While trying to set up my app, create a local database, and insert the very first user who has logged in locally, I encountered an error message at a specific point in the code. Here's where it happened: angular.module("greenApp") .service("d ...

Managing the "Accept Cookies" notification using Selenium in JavaScript

As I use Selenium to log in and send messages on a specific website, I am faced with a cookie popup that appears each time. Unfortunately, clicking the accept button to proceed seems to be quite challenging for me. Here is an image of the cookie popup Th ...

Encountering an issue while trying to verify user registration in MySQL using Node.js Express. During the user registration process, an error arises indicating that 'res' is not defined

import React from 'react' import { Link } from 'react-router-dom' import {useNavigate} from 'react-router-dom'; import { useState } from 'react' axios from "axios" const Register = () => { const [i ...

Transferring variables from the existing scope to a compiled directive

I'm having trouble passing an object from the current scope to a directive that I added using the $compile service. While I can successfully pass a string to the child directive, I'm unable to pass the actual object. Take a look at this fiddle ...

Resizing an image with six corners using the canvas technique

Currently, I am facing two issues: The topcenter, bottomcenter, left and right anchors are not clickable. I'm struggling with the logic to adjust the image size proportionally as described below: The corner anchors should resize both height and wi ...

The issue with AngularJS routes where scrolling remains static even after transitioning to a different state

I have a question about scrolling behavior in my application. Currently, when I scroll down and switch to a different state using $state.go('other_template'), the new state loads but the scroll position remains the same as before. Is there a way ...

What is the best way to display Redis data in express.js?

As a beginner in node.js and express.js, I find myself stuck on a problem that I'm hoping someone can help me solve. I have data stored in Redis. redis 127.0.0.1:6379> hgetall "store1" 1) "apple" 2) "10" 3) "banana" 4) "15" 5) "pear" 6) "20" 7) "n ...

There appears to be an issue with the functionality of the external CSS pathway

placeholder image hereplaceholder image hereplaceholder image here I'm encountering a problem and struggling to identify the mistake in my current approach. ...

Using v-for to display the children of each object in individual divs, while also avoiding any sorting functions

Encountered an interesting "issue" while working with vue-3: First, let's take a look at the data structure I am using: export const datatwo = [ {id: "1", artist: "Yaakov Shwekey", dateadded: "07/04/2022", artistroute: "/yaakovshwekey", albums: [{al ...