📜  i18n vue cli (1)

📅  最后修改于: 2023-12-03 15:31:20.998000             🧑  作者: Mango

i18n with Vue CLI

Introduction

Internationalization (i18n) is the process of adapting your application to support different languages (locales) and cultures. i18n is an important feature for any application that aims to reach a global audience.

Vue CLI provides built-in support for i18n with the vue-i18n library. This allows you to easily implement translations for your Vue.js application.

Getting Started

To get started with i18n in Vue CLI, you first need to install the vue-i18n library:

npm install vue-i18n --save

Once you have installed vue-i18n, you can create a new locale file in your project. For example, you can create a file called en-US.js in the src/i18n/ folder to define the English (US) translations for your application.

Here is an example of what the en-US.js file could look like:

export default {
  greeting: 'Hello, World!',
  welcome: 'Welcome to my App!',
  button: {
    submit: 'Submit'
  }
}

Next, you will need to configure Vue CLI to use the vue-i18n library. This is done by adding the following code to your main.js file:

import VueI18n from 'vue-i18n'
import messages from './i18n'

Vue.use(VueI18n)

const i18n = new VueI18n({
  locale: 'en-US', // set default locale
  messages // set locale messages
})

new Vue({
  i18n,
  render: h => h(App)
}).$mount('#app')

The code above initializes the VueI18n plugin and sets the default locale to 'en-US'. It also loads the translations defined in the en-US.js file.

Using Translations

Once you have defined your translations and configured the VueI18n plugin, you can start using translations in your Vue components.

Here is an example of a Vue template that uses translations:

<template>
  <div>
    <h1>{{ $t('greeting') }}</h1>
    <p>{{ $t('welcome') }}</p>
    <button>{{ $t('button.submit') }}</button>
  </div>
</template>

<script>
export default {
  // ...
}
</script>

In the code above, the {{$t}} syntax is used to access the translated values. The $t method takes a translation key as its argument, and returns the translated value.

Conclusion

i18n is an important feature for any application that aims to reach a global audience. With the vue-i18n library and Vue CLI, implementing i18n in your Vue.js applications is easy and straightforward. By following the steps outlined in this guide, you should now have a basic understanding of how to implement i18n in your Vue CLI projects.