0

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

hidar
  • 5,449
  • 15
  • 46
  • 70

1 Answers1

3

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.

Prashant
  • 7,340
  • 2
  • 25
  • 24
  • this is a good answer, but only for those who want translation. I am looking on how to get `this.` inside an export default{} file – hidar Mar 26 '18 at 16:25
  • You can't. export default runs in its own context and therefore has its own this. Vue components runs in its component context and has its this set to the vue instance. Which is why you can get access to this.$t within the components. – Prashant Mar 26 '18 at 16:37
  • but there must be a workaround for this right? it might be hard but not impossible – hidar Mar 26 '18 at 16:39
  • Highly recommend not to screw with this context of the javascript modules. – Prashant Mar 26 '18 at 16:45
  • @hidar, you should not mutate the 'this' context of your component or module but still if you want to do that, you can try `this = Object.assign(this, i18n)` – Himanshu Mittal Mar 27 '18 at 10:12