The Vue.js application which utilizes Vue I18n encountered the error message: "Unable to define i18n due to TypeError"

I am currently working on implementing internationalization in my Vue.js project using Vue I18n.

Although I've been following the documentation found at , I encountered the following error message:

[Vue warn]: Error in render: "TypeError: i18n is undefined"

found in

---> <MainNavBar> at src/components/MainNavBar.vue
       <VApp>
         <App> at src/App.vue
           <Root> vue.runtime.esm.js:619 

TypeError: "i18n is undefined"
    $t vue-i18n.esm.js:167
    render MainNavBar.vue:33
    VueJS 42
    <anonymous> main.js:18
    js app.js:6991
    __webpack_require__ app.js:724
    fn app.js:101
    0 app.js:7304
    __webpack_require__ app.js:724
    <anonymous> app.js:791
    <anonymous> app.js:1 vue.runtime.esm.js:1887
    VueJS 45
    <anonymous> main.js:18
    js app.js:6991
    __webpack_require__ app.js:724
    fn app.js:101
    0 app.js:7304
    __webpack_require__ app.js:724
    <anonymous> app.js:791
    <anonymous> app.js:1

It's puzzling to me why i18n is showing as "undefined", even though I have installed it through NPM following the documentation.

Could someone provide assistance with this issue?

I have already tried searching for a solution online, but unfortunately, I haven't had any luck.

In order to aid in troubleshooting this problem, below is the code that I am currently using.

Thank you kindly.

MainNavBar.vue

<i18n>
{
  "en": {
     "home": "Home"
  },
  "pt": {
     "home": "Início"
  }
}
</i18n>

<template>
  ...
  < li class = "nav-item">
    <router-link class="nav-link" to='/home'>
      < i class="fa fa-home"></i> {{ $t('home') }}
    </router-link>
  </li>
  ...
</template>

<script>
export default {
  data () {
    return {
      locale: 'en'
    }
  },
  watch: {
    locale (val) {
      this.$i18n.locale = val
    }
  }
}
</script>

main.js

import 'vuetify/dist/vuetify.min.css'

import Vue from 'vue'
import Vuetify from 'vuetify'
import VueI18n from 'vue-i18n'

import App from './App.vue'
import router from './router'
import store from './store'

Vue.use(Vuetify)
Vue.use(VueI18n)

Vue.config.productionTip = false

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

vue.config.js

const merge = require('deepmerge')

module.exports = {
  chainWebpack: config => {
    config.module
      .rule('vue')
      .use('vue-loader')
      .tap(options =>
        merge(options, {
          loaders: {
            i18n: '@kazupon/vue-i18n-loader'
          }
        })
      )
  }
}

package.json

{
  "name": "executive_frontend",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "serve": "vue-cli-service serve",
    "build": "vue-cli-service build",
    "lint": "vue-cli-service lint",
    "test:e2e": "vue-cli-service test:e2e",
    "test:unit": "vue-cli-service test:unit"
  },
  "dependencies": {
     "axios": "^0.18.0",
     "bootstrap": "^4.3.1",
     "jquery": "^3.3.1",
     "material-design-icons-iconfont": "^4.0.5",
     "ol": "^5.3.1",
     "popper.js": "^1.14.7",
     "vue": "^2.6.7",
     "vue-i18n": "^8.10.0",
     "vue-router": "^3.0.1",
     "vuetify": "^1.5.6",
     "vuex": "^3.0.1"
   },
   "devDependencies": {
    "@kazupon/vue-i18n-loader": "^0.3.0",
    "@vue/cli-plugin-babel": "^3.4.0",
    "@vue/cli-plugin-e2e-nightwatch": "^3.4.0",
    "@vue/cli-plugin-eslint": "^3.4.0",
    "@vue/cli-plugin-unit-jest": "^3.4.0",
    "@vue/cli-service": "^3.4.0",
    "@vue/eslint-config-standard": "^4.0.0",
    "@vue/test-utils": "^1.0.0-beta.20",
    "babel-core": "7.0.0-bridge.0",
    "babel-eslint": "^10.0.1",
    "babel-jest": "^23.6.0",
    "deepmerge": "^3.2.0",
    "eslint": "^5.8.0",
    "eslint-plugin-vue": "^5.0.0",
    "node-sass": "^4.11.0",
    "sass-loader": "^7.1.0",
    "vue-template-compiler": "^2.5.21"
  }
}

Answer №1

In order to properly initialize Vue, ensure that you provide an i18n instance to the constructor.

Here is an example of how to create the instance:

const i18n = new VueI18n({
    locale: "en", // default locale
    messages: {
        en: { // messages in English },
        fr: { // messages in French }
    },
})

Then, make sure to pass this instance when initiating Vue:

new Vue({
    i18n,
    router,
    ...
})

Answer №2

No need for Watchers here. Use the method below instead:

<template>
  <select @change="update">
    <option value="en">English</option>
    <option value="es">Español</option>
    <option value="ru">Русский</option>
  </select>
</template>

<script>
export default {
  methods: {
    update(e) {
      this.i18n.locale = e.target.value
    }
  }
}
</script>

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

Step-by-step guide on writing to a JSON file using Node.js

I am currently developing a Facial Recognition web application using React for the frontend and Node.js for the backend. You can find more information about my project here. So far, I have completed the frontend part where users manually add 128-d descript ...

Comparing Watch and $watch: Understanding the Distinctions

Let's ponder a question. What sets apart options from instance methods? In the context of a watch example, we can utilize a watcher as an option (https://v3.vuejs.org/api/options-data.html#watch) or as a method of an instance (https://v3.vuejs.org/a ...

The accumulation of input using setInterval is not effective

I need some help with my code. Please take a look at this link here. I want the input to count up from zero and hide when I click the "change" button. But when I show the input again, I want its value to reset back to zero. Can anyone guide me on how to ...

Challenges arise when integrating ng-model with Angular Chosen

I'm working with a table that lists users, each row ending with a button that triggers a popup form. Inside the popup, I'm using a multiple select feature with Angular Chosen to display each user's 'interests'. However, despite fet ...

The CORS policy has blocked the AWS API Gateway request originating from 'http://localhost:8080'

Currently, I am facing an issue with deploying an API for use in Front End. The API functions properly when tested alone, but it returns a CORS error when integrated into a Vue app. The specific error message is as follows: Access to XMLHttpRequest at &a ...

Tips for mocking constructors in AngularJS, specifically the Date() constructor

Trying to verify a function which receives millisSinceEpoch and gives back the time if it is today's date, otherwise it gives the date. getLocaleAbbreviatedDatetimeString: function(millisSinceEpoch) { var date = new Date(millisSinceEpoch); if (d ...

Injecting variable styles into my VueJS component

I am currently working on developing a custom progress bar to visualize the percentage of completed tasks. The approach I am taking involves using v-bind:styles and passing {width: dynamicWidth + '%'} to regulate the progression of the bar. To ac ...

Utilizing the Data Fetched from a Factory GET Request in an AngularJS Controller

Recently, I developed an Angular factory specifically designed for fetching JSON data. Utilizing the $resource alongside the get method has allowed me to successfully retrieve a JSON object from the server. Within this object are multiple child objects tha ...

Using jQuery to reload the page following a PHP form submission

Currently facing an issue as I am trying to load the same page submitted by PHP, specifically in a comment section. After users submit their message, I want to display the existing comments along with the new one. The problem arises because I'm not u ...

Similar Functionality to jQuery's .load() in REACT

I'm currently diving into the world of React, attempting to transition a PHP + jQuery Page to React (minus the jQuery). However, given the intricate complexity of the page, I won't be able to migrate everything at once. As a result, I need to sta ...

Attempting to create a JavaScript class within an HTML document

Having an issue with instantiating a JavaScript class in a separate HTML file. The JavaScript class looks like this: class Puzzle { constructor(fenStart, pgnEnd) { this.fenStart = fenStart; this.pgnEnd = pgnEnd; } } module.exports = Puzzle; ...

Using a Regex Pattern to Validate Password Strength

var pattern = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[!@#$%^&*()~])[a-zA-Z0-9!@#$%^&*()~]+$/; var password = document.getelementbyId("txtPassword").value; if(!pattern.test(password)) { alert("Invalid Password. Please make sure it contains at ...

Exploring the perfect blend of ReactJs Router Links with material-ui components, such as buttons

I am currently facing a challenge in integrating the functionality of react router with material ui components. For example, I have a scenario where I want to combine a router and a button. I attempted to merge them together and customize their style. In ...

Encountered an Error: UpdateCommand is not a valid constructor - AWS SDK v3 when running unit tests with Jest in Node.js

Every time the unit test reaches the point where it calls the UpdateCommand from @aws-sdk/lib-dynamodb, I encounter an error saying "TypeError: UpdateCommand is not a constructor". I suspect that there might be an issue with the mock. I'm unsure of ho ...

Reveal the MongoDB database connection to different sections within a Next.js 6 application

Currently developing an application using Next.js v6, and aiming to populate pages with information from a local mongodb database. My goal is to achieve something similar to the example provided in the tutorial, but with a twist - instead of utilizing an ...

What could be causing the appearance of a mysterious grey box hovering in the upper left portion of my image and why is the code only adjusting the size of the grey box instead of the entire

I've been working on embedding some JavaScript into my Showit website to create a drag-and-drop feature that displays a collage/mood board effect. Everything is functioning correctly, but I'm running into issues with resizing the images. There&a ...

VueJS with Vuetify: Issue with draggable cards in a responsive grid

I am currently working on creating a gallery that allows users to rearrange images. To test this functionality, I am using an array of numbers. It is important that the gallery is responsive and displays as a single column on mobile devices. The issue I ...

Dirty context detected in Material-UI TextField

Trying to understand how to check for dirtyness with material-ui's FormControl or TextField component. The TextField demo page mentions that TextField is made up of smaller components (FormControl, InputLabel, Input, and FormHelperText) which can be c ...

"Encountered a 400 Error while trying to access the OpenAI

var openairequest = new XMLHttpRequest(); const payload = ({ "model": "text-davinci-003", "prompt": "say this is a test" }); console.log(payload) openairequest.open("POST",`https://api.openai.com/v ...

What are some effective tactics for reducers in react and redux?

Working on a React + Redux project to create a web app that communicates with an API, similar to the example provided at https://github.com/reactjs/redux/tree/master/examples/real-world. The API I'm using returns lists of artists, albums, and tracks, ...