show of an example of using vue-i18n in typescript

Here's an example of using vue-i18n in TypeScript:

  1. First, install the package:

npm install vue-i18n

  1. Then, create a file i18n.ts in your project:
index.ts
import Vue from 'vue';
import VueI18n from 'vue-i18n';

Vue.use(VueI18n);

const messages = {
  en: {
    hello: 'Hello!',
  },
  fr: {
    hello: 'Bonjour!',
  },
};

const i18n = new VueI18n({
  locale: 'en',
  fallbackLocale: 'en',
  messages,
});

export default i18n;
273 chars
22 lines
  1. In your component, import the i18n instance and use it like this:
index.ts
<template>
  <div>{{ $t('hello') }}</div>
</template>

<script lang="ts">
  import { Vue, Component } from 'vue-property-decorator';
  import i18n from './i18n';

  @Component({
    name: 'MyComponent',
    i18n,
  })
  export default class MyComponent extends Vue {
    // ...
  }
</script>
292 chars
17 lines

Here we use the $t function provided by vue-i18n to translate the string hello according to the current locale.

Note: make sure to configure your TypeScript compiler to recognize .vue files, or use .ts files instead of .vue files for your components.

related categories

gistlibby LogSnag