Skip to content

Instantly share code, notes, and snippets.

@james2doyle
Last active November 6, 2020 22:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save james2doyle/3b10dca9697b556820da5e0aeca57d90 to your computer and use it in GitHub Desktop.
Save james2doyle/3b10dca9697b556820da5e0aeca57d90 to your computer and use it in GitHub Desktop.
Call the $t method on the shared Vue instance programmatically in Nuxt
// later versions of Nuxt have errors with original code
import VueI18n from 'vue-i18n';
/**
* Translate a string
*
* @param {string} key
*
* @returns {string}
*/
const intl = function(key: string): string {
try {
const i18n = new VueI18n({
locale: 'en',
fallbackLocale: 'en',
messages: {
en: require('@/lang/en.json'),
},
});
return i18n.t(key).toString();
} catch (e) {
console.error(e);
}
return key;
};
export default intl;
import Vue from 'vue';
/**
* Translate a string
*
* @param {string} key
*
* @returns {string}
*/
const intl = function(key: string): string {
// access the current vue instance and alias it for export
return Vue.prototype.$nuxt.$t(key);
};
export default intl;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment