Search code examples
javascriptvue.jsvuejs2vue-i18n

how do I access `this.` in exported in vuejs


I have some files that return simple data, like mutation.js for vuex but generally they are just like this:

export default {
 ...
 someFunction() {}
 ...
}

Right now, I would like to access this. so I can use the vue-i18n translation like this.$t('TRANS_TOKEN') but for some reason I am not able to use this. I am thinking about including vue in this file as: import vue from 'vue' and probably do vue.$t(..) if it works but I tried it and it doesn't


Solution

  • First a question. Why doing translations in mutations file? I'd keep translations in your components only.

    You can however achieve what you want, by doing so

    // i18n.js
    const i18n = new VueI18n();
    
    export default i18n;
    
    // main.js
    import VueI18n from 'vue-i18n';
    import i18n from './i18n.js';
    
    Vue.use(VueI18n);
    
    new Vue({
        i18n,
        ...
    });
    
    // Anywhere else, grab the i18n instance to do translations
    import i18n from './i18n.js';
    
    i18n.t('translate this');
    

    Documentation on all the methods available on the VueI18n instance.