Use Vue-i18n in Vuex store

Posted on: 2018-08-24

Here is a good way to configure Vue-i18n so you can use it in your Vuex Store

First, create a file just to configure the internationnalization, we can name it i18n.js, at the root of our project.

import Vue from 'vue'; import VueI18n from 'vue-i18n'; import moment from 'moment'; Vue.use(VueI18n); // if you are using moment in your project, now is a good time // to set its locale also moment.locale(locale); const i18n = new VueI18n({ locale, // global variable holding the local value messages, // globale variable holding translations }); export default i18n;

The in your main.js file :

import i18n from './i18n'; // ... new Vue({ i18n, el: `#app`, router, components: { App }, template: `<App/>`, store, });

And in your Vuex Store (I am using vue-toasted to display messages in a toaster) :

import axios from 'axios'; import Vue from 'vue'; import moment from 'moment'; import i18n from '../../i18n'; export default { state : { // ... }, mutations : { // ... }, actions : { doSomething ({ dispatch }, data) { return`/api/something`, data) .then(res => { Vue.toasted.success(`store.success_doing_something`)); }) .catch(() => { Vue.toasted.error(`store.error_while_doing_something`)); return Promise.reject(); }); }, }, };