Utilizing i18n within the Vuex store: A guide

I am grappling with an issue in my project where I need to perform translations within the Vuex store. Every time I attempt to translate using i18n inside the store, an error occurs.

I have attempted to import and utilize i18n inside the store by using the following import statement. However, it results in the error

Uncaught TypeError: _i18n__WEBPACK_IMPORTED_MODULE_3__.default.t is not a function

import i18n from '@/i18n';

In the main.js file of my Vue project, I import and implement the i18n file as follows:

import { createApp } from 'vue';
import App from './App.vue';
import router from './router';
import { store } from './store';
import i18n from './i18n';

createApp(App).use(i18n).use(store).use(router).mount('#app');

This snippet represents my i18n.js file located within the src directory:

import { createI18n } from 'vue-i18n';

function loadLocaleMessages() {
  const locales = require.context(
    './locales',
    true,
    /[A-Za-z0-9-_,\s]+\.json$/i
  );
  const messages = {};
  locales.keys().forEach((key) => {
    const matched = key.match(/([A-Za-z0-9-_]+)\./i);
    if (matched && matched.length > 1) {
      const locale = matched[1];
      messages[locale] = locales(key);
    }
  });
  return messages;
}

export default createI18n({
  legacy: false,
  locale: localStorage.locale ?? 'nl',
  globalInjection: true,
  messages: loadLocaleMessages(),
});

Answer №1

Are you a Vue 3 developer facing challenges with implementing i18n in your Vuex store? Fear not, as I have found a solution that works well:

translations/index.js featuring a simple setup

import { createI18n } from 'vue-i18n'

const i18n = createI18n({
    fallbackLocale: 'en',
    globalInjection: true,
    messages: messages
})

export default i18n

main.js Simply import your store and i18n, then integrate them into your Vue app instance

import i18n from './translations'
import store from './store'

const app = createApp(App)

app.use(store)
app.use(i18n)
app.mount('#app')

For those working on a Vuex store module file and needing a getter example:

import i18n from './translations'

const getters = {
  getNotification: (state) => {
      ...
      notification.title = i18n.global.t('notification.title')
      ...
  }
}

Answer №2

If you're working with Vuex and Vue-i18n, here is a helpful setup:

Start by creating a vue-i18n.js file like the following example;

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

// List of localization languages
import { locale as en } from "@/core/config/i18n/en.js";
import { locale as ch } from "@/core/config/i18n/ch.js";

Vue.use(VueI18n);

let messages = {};
messages = { ...messages, en, ch };

// Retrieve currently selected language
const lang = localStorage.getItem("language") || "en";

// Create VueI18n instance with options
const i18n = new VueI18n({
  locale: lang,
  messages
});

export default i18n;

Next, import this file into your main.js in Vue;

import i18n from "@/core/plugins/vue-i18n";

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

Import it within your Vuex store or modules (like I did in my vuex module);

import i18n from "@/core/plugins/vue-i18n";

Then you can use it wherever needed, whether it's in an action, mutation, setter, or getter;

const sample = i18n.t('ERRORS.NETWORKERROR');

In the en.js file, define your English localization strings;

export const locale = {
  LOGIN: {
    OPERATORID: "Operator ID",
    SIGNIN:"Sign In",
    SCANCARD: "Scan Card"
  },
  ERRORS: {
    NETWORKERROR: "Network error occurred!",
    UNAUTHUSERERROR: "Unauthorized user!",

  }
};

Answer №3

Utilizing this.$i18n within my store is possible:

this.$i18n.t('campaign.setPhotocredit-error')

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

After making an Ajax call using AngularJS in a PHP file, I expected to receive only a success or fail message. Instead, I received the entire HTML page code along

After making an Ajax call using AngularJS in a PHP file, I expected to receive only a success/fail message. However, I ended up receiving the full HTML page code along with tags. Here is my AngularJS code: $http.post('ajax_Location.php',{ &apos ...

Consistent Failure: jQuery File Upload consistently aborts with the error message 'File upload aborted'

I'm currently utilizing the Blueimp File Upload Plugin to facilitate file uploads to a remote server. The HTML code snippet for the file upload input is as follows: <input id="fileupload" type="file" name="files[]" data-url="http://my-server-ip/u ...

determining the total invoice amount and the quantity of items in a React array of objects

Currently, I am working on an online shopping app built in React. Within this app, there is an Invoice array named invItems, which contains various products referred to as items. My goal is to calculate the total price by multiplying the quantity of each i ...

Customize Vue components for easy drag and drop functionality

I am attempting to implement custom draggable components using the vuedraggable package, but I am facing issues in making it work. Additionally, I want the functionality to copy the component instead of moving it altogether. Below is the code snippet: < ...

Maintain visibility of Bootstrap side menu

I noticed on the Bootstrap website there is a sidebar with sticky links that stay in view as you scroll. They also highlight each menu item when it's in view. I've tried replicating this on my own website, but can't figure out how to make it ...

Angular2: the setTimeout function is executed just a single time

Currently, I am working on implementing a feature in Angular2 that relies on the use of setTimeout. This is a snippet of my code: public ngAfterViewInit(): void { this.authenticate_loop(); } private authenticate_loop() { setTimeout (() =& ...

Establishing global credentials in VueJS using Axios

When working in main.js, I included the following code: axios.defaults.withCredentials = true; Although this should make it work, I found that the cookies were not being sent to the back end. I inspected the request header and noticed something strange: ...

Why are the links in the navgoco slide menu failing to function properly?

I utilized a demo from jQueryRain to create a collapsible menu using jQuery. However, after completion, I discovered that none of the links were functioning properly. Upon visiting the documentation page, I noticed that many users were encountering the sam ...

POST request using Axios fails to authenticate with JWT token, yet the GET request is successfully authenticated

I'm currently working on setting up a REST API in Django to be connected with Vue.js on the front end. The connection is made using the axios library along with JWT token authentication. However, I've encountered an issue where Django responds w ...

What is the best way to enable a service to retrieve variables from the Controller?

My controller has variables declared on the $scope and two arrays that hold objects: one for available groups and the other for groups the user is already a part of. The addUserToGroups() function sends a call to the server to add the user to the selected ...

How to pass variables in AngularJS

When displaying data in a grid, I need to change the button icon on click of the active or inactive button. The functionality is working well, but I am having trouble finding the clicked active button to change its icon. In jQuery, we can use "this", but ...

Is it permissible for me to incorporate a package from the dependencies listed in the package-lock.json file into my

I'm looking to incorporate date-fns into my project. I currently have react-datepicker, which also uses date-fns. Can I simply utilize date-fns from react-datepicker, or do I need to install it separately in my project? ...

Is there a way for me to retrieve the UrlMatcher from ui-router?

While exploring the ui-router documentation, I came across an object called UrlMatcher. This object contains useful methods like exec, but I am struggling to find clear instructions on how to access it. Nevertheless, the documentation page provides a detai ...

Incorporate a React web application seamlessly into a React Native WebView component

In my monorepo, I have a web app and a mobile app (built with React and React Native respectively). My goal is to embed the web app into the mobile app using React Native WebView. After reading the documentation, I learned that the source for the WebView ...

Enable the use of multiple decimal separators in a ReactJS application

I am currently developing a small project that involves using a POST request, which requires multiple fields with 2 float values. My backend system expects the decimal separator to be a ".", but my target audience is primarily French and they ar ...

Utilizing a drop-down menu in AngularJS to dynamically change a URL and fetch images

Currently, I am in the process of creating a website using AngularJS that accesses images from reddit and showcases them based on various parameters such as number of votes and date posted. While this is not groundbreaking, my main goal is to enhance my sk ...

Revamp the usage of $fetch in nuxt3 by implementing a global onRequest handler

Would it be feasible to utilize a global onRequest handler in Nuxt3 to $fetch data and append specific details to each request? It was a straightforward process with nuxt2 and axios /plugins/axios.js export default function ({ $axios, store, req }) { $a ...

Converting a JSON array into an object representation

I have received some JSON data that has a specific structure: [ { "items": [ { "id": "xxxx", "description": { "style": "", "specs": "" } }, { "id": ...

Error when trying to add style-loader in Vue.js 2 due to webpack installation issue

My task is to set up the style-loader in order to load import 'bootstrap-icons/font/bootstrap-icons.css'. However, when I run npm install style-loader, I encounter the following error message: npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to re ...

What is the process for altering the active status in pagination?

How can I make the active class in my pagination appear in red? Here's the code snippet I have: In my script.js file: $(".pagination").append("<li class='page-item' id='previous-page'><a class='page-li ...