Warm tip: This article is reproduced from stackoverflow.com, please click
vue.js vuepress

How to use vue-i18n in custom VuePress components?

发布于 2020-08-11 21:18:03

I'm using the VuePress framework to build a multilingual website for my project. The Internationalization Guide in the VuePress docs is quite helpful, but it doesn't explain, how to translate custom Vue.js components in the .vuepress/components/ directory.

From what I gathered, the best solution would be to integrate the vue-i18n plugin with VuePress, but there appears to be no guidance on how to do that?

Questioner
tillsanders
Viewed
7
tillsanders 2020-08-05 21:11

This might not be the perfect solution, but it works as intended:

  1. Follow the Internationalization Guide and set up multiple locales.
  2. Install vue-i18n: npm i vue-i18n.
  3. Assuming you are using the default theme, we will extend that to hook vue-i18n into it. Create a custom theme directory: mkdir ./.vuepress/theme/.
  4. Add an index.js file to the newly created theme directory:
// .vuepress/theme/index.js

module.exports = {
  extend: '@vuepress/theme-default' // extend the default VuePress theme
}
  1. Install vue-i18n by adding another file to the same directory, the enhanceApp.js file which allows you to do some App Level Enhancements:
// .vuepress/theme/enhanceApp.js

import VueI18n from 'vue-i18n'

export default ({ Vue, options }) => {
  Vue.use(VueI18n);

  options.i18n = new VueI18n({
    locale: 'en',
  });
}
  1. In your custom components, you can set the current locale passing on the global computed property $lang:
// .vuepress/components/Foo.vue

export default {
  mounted() {
    this.$i18n.locale = this.$lang;
  },
  i18n: {
    messages: {
      'en-US': { title: 'Foo' },
      'de-DE': { title: 'Bar' }
    }
  }
};

I found no simple solution to hook into the root component to set the current locale globally. Maybe someone else has a hint on how to achieve this nicely?