To achieve the same outcome, follow these steps:
Step 1: Create a separate index.ts file within an i18n folder (you can choose the root level or any other location in your app)
i18n/index.ts
import Vue from 'vue';
import VueI18n from 'vue-i18n';
// Register the i18n module
Vue.use(VueI18n);
const i18n = new VueI18n({
locale: 'nb-NO', // Use "window.navigator.language" to get the browser language
fallbackLocale: 'en',
messages: {en, no},
silentTranslationWarn: true
})
const translate = (key: string) => {
if (!key) {
return '';
}
return i18n.t(key);
};
export { i18n, translate}; // Export the above method
Step 2: Ensure that you use(import) the code above in main.ts
main.ts
import { i18n } from '@/i18n';
new Vue({ i18n, render: h => h(app) }).$mount('#app')
After configuring the above steps, you will be able to use translations anywhere in your application.
Step 3: How to use it in .ts and .vue files
// First import it into the file
import { translate, i18n } from '@/i18n';
// This is how we can use translation inside HTML templates
<template>
<h1>{{'sample text' | translate}}</h1>
</template>
// This is how we can use translation inside .ts or .vue files
<script lang='ts'>
// Normal scenario
testFunc(){
let test = `${translate('sample text')}`;
console.log(test );
}
// In your case, it should be like this:
(()=>{
const test = `${translate('auth.title')}`;
console.log(test)
})()
</script>
I trust that these guidelines will assist you in resolving your issue.