To avoid unnecessary duplicate document content, some of the documents in this library are linked to the content in
i18n-pro
Thei18n-pro
related link in the current document is based on the2.0.0
version. If you are using a different version, you need to check the document corresponding to the version you are using to avoid inconsistent usage
Table of Contents
1. Install
2. Access API
Configure Initial State
Register Plugin
Wrap Translation Text
with $t
3. Initialize Command Line Configuration File
4. Adjust i18nrc.js
Configuration
5. Execute Translation Command
6. Importing Language Pack
7. Switch Language
8. Demo
npm i @i18n-pro/vue2
# or
yarn add @i18n-pro/vue2
# or
# Note: To prevent issues where the i18n command cannot be used due to ghost dependencies, it is essential to install i18n-pro when using pnpm
pnpm i i18n-pro @i18n-pro/vue2
// i18n.ts
import { createI18n } from '@i18n-pro/vue2'
export default createI18n({
namespace: 'testNamespace',
})
// main.ts
import Vue from 'vue'
import App from './App.vue'
import i18n from './i18n'
Vue.use(i18n)
new Vue({
el: '#app',
render: h => h(App)
})
// App.tsx
<template>
<div> {{ $t('hello world') }} </div>
</template>
The language pack already exists, so it needs to be applied to the project
If the generated language pack is a separate file form (output.langType == 'multiple'
) for each language, the operation is as follows:
// i18n.ts
import { createI18n } from '@i18n-pro/vue2'
+ import zh from './i18n/zh.json'
+ import ja from './i18n/ja.json'
export default createI18n({
namespace: 'testNamespace',
+ locale: 'zh',
+ langs: {
+ zh,
+ ja,
+ },
})
If the generated language pack is in the form of aggregation (output.langType == 'single'
), the operation is as follows:
// i18n.ts
import { createI18n } from '@i18n-pro/vue2'
+ import langs from './i18n/langs.json'
export default createI18n({
namespace: 'testNamespace',
+ locale: 'zh',
+ langs,
})
At this point, the project has been completely connected to internationalization. The above locale
specifies any of the target language, and the translated content can be seen on the page. If there are new Translation Text
(need to be wrapped with $t
function) in the subsequent project, you only need to execute the translation command npx i18n t
again to generate the latest language package
You can switch languages through $setI18n
// App.tsx
<template>
<div> {{ $t('hello world') }} </div>
+ <select
+ :value="$i18nState.locale"
+ @change="onSelectChange"
+ >
+ <option value="zh">简体中文</option>
+ <option value="en">English</option>
+ <option value="ja">日本語</option>
+ </select>
</template>
+
+ <script>
+ export default {
+ methods: {
+ onSelectChange(e){
+ this.$setI18n({
+ locale: e.target.value,
+ })
+ },
+ }
+ }
+ </script>
Real code examples can refer to Live Demo in the README
document