Search code examples
javascriptinternationalizationvue-i18n

How to import i18n in Vue file


I am using i18n library in Vue.js for language translation. I want to to import in it my script and store a value in data, but I have trouble with importing it. How should I import it? I tried with import $t from "./i18n"; but that just returns this error: Module not found: Error: Can't resolve './i18n'

here is my code:

script>
import Header from "../components/Header";
import $ from "jquery";
import $t from "./i18n";

export default {
  name: "GroupPermissions",
  components: {
    Header
  },
  data() {
    return {
      showAddGroupDialog: false,
      updatePermissionDialog: false,
      itemsToBeDeleted: [],
      permissions: $t("groupPermissions.table.permissions")
    };

and my main.js:

import Vue from "vue";
import App from "./App.vue";
import router from "./router";

import "bootstrap";
import "bootstrap/dist/css/bootstrap.min.css";

import VueMaterial from "vue-material";
import "vue-material/dist/vue-material.min.css";
import "vue-material/dist/theme/default.css";
import "vue-multiselect/dist/vue-multiselect.min.css";
import $ from "jquery";
import Multiselect from "vue-multiselect";
import i18n from "./i18n";
import "@/plugins/echarts";
import Sticky from 'vue-sticky-directive'

Vue.component("multiselect", Multiselect);
Vue.use(VueMaterial);
Vue.use(Sticky);

Vue.config.productionTip = false;

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

Solution

  • If you'd like use vue-i18n, in your main.js you should import vue-i18n library first and create an i18n variable like this:

    import VueI18n from 'vue-i18n';
    
    const i18n = new VueI18n({
        locale: 'en',
        messages: { 'en': { title: 'Title' }},
    });
    

    and pass the i18n var to your Vue in main.js as you did it:

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

    After this, in your component you will have a this.$t('title') method that will return with 'Title' value.

    This link may help for you: http://kazupon.github.io/vue-i18n/started.html#javascript