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

4
  • Did you do Vue.use() on your imported component? Commented Mar 25, 2018 at 7:08
  • It is actually a mutation file, it just exports some functions Commented Mar 25, 2018 at 7:23
  • You should include the translated text as argument to the commit. Commented Mar 25, 2018 at 10:11
  • isn;t there a better way though? Commented Mar 25, 2018 at 12:24

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

5 Comments

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
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.
but there must be a workaround for this right? it might be hard but not impossible
Highly recommend not to screw with this context of the javascript modules.
@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)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.