๐ Getting started โ
To begin, you'll need to install vue-next-i18n
use npm โ
npm install vue-next-i18n
use yarn โ
yarn add vue-next-i18n
๐ Usage โ
When using with a module system, you must explicitly install the vue-next-i18n via app.use():
typescript
// 1. Ready translated locale messages
// The structure of the locale message is the hierarchical object structure with each locale as the top property
const messages = {
en: {
message: {
hello: 'hello world'
}
},
zhCHS: {
message: {
hello: 'ไฝ ๅฅฝ ไธ็'
}
},
ja: {
message: {
hello: 'ใใใซใกใฏใไธ็'
}
}
}
// 2. Create i18n instance with options
import { createApp } from 'vue';
import { createI18n } from 'vue-next-i18n';
const i18n = createI18n({
locale: 'zhCHS', // set locale, depend on messages object structure keys
messages, // set locale messages
localeKeys:['zhCHS','zhCHT','en'] //Not required, default value๏ผ ['zhCHS','zhCHT','en']
})
// 3. Create a vue root instance
const app = createApp({
// set something options
// ...
})
// 4. Install i18n instance to make the whole app i18n-aware
app.use(i18n)
// 5. Mount
app.mount('#app')
// Now the app has started!
HTML โ
<div id="app">
<p>{{ $t("message.hello") }}</p>
</div>
<!-- Output the following: -->
<div id="#app">
<p>ไฝ ๅฅฝ ไธ็</p>
</div>
๐ Composition API โ
typescript
import { useI18n } from 'vue-next-i18n'
export default {
setup() {
const i18n = useI18n()
const { currentLocale, changeLocale } = i18n
return {
currentLocale,
changeLocale
}
}
}
๐ฆ API Examples โ
basic โ
const messages = {
en: {
message: {
hello: 'hello world'
}
},
zhCHS: {
message: {
hello: 'ไฝ ๅฅฝ ไธ็'
}
},
ja: {
message: {
hello: 'ใใใซใกใฏใไธ็'
}
}
}
<div id="app">
<p>{{ $t("message.hello") }}</p>
</div>
support function โ
const messages = {
en: {
message: {
hello: (val) => `hello world ${val}`
}
},
zhCHS: {
message: {
hello: (val) => `ไฝ ๅฅฝ ไธ็ ${val}`
}
},
ja: {
message: {
hello: (val) => `ใใใซใกใฏใไธ็ ${val}`
}
}
}
<div id="app">
<p>{{ $t("message.hello",'hahaha') }}</p>
</div>
support $n replacement โ
Inserts the n th (1-indexed) available
const messages = {
en: {
message: {
hello: `hello world $1,$2,$3...`
}
},
zhCHS: {
message: {
hello: `ไฝ ๅฅฝ ไธ็ $1,$2,$3...`
}
},
ja: {
message: {
hello:`ใใใซใกใฏใไธ็ $1,$2,$3...`
}
}
}
// output: hello world param1,param2,param3
<div id="app">
<p>{{ $t("message.hello",'param1','param2','param3') }}</p>
</div>
use array messages โ
The array order depends on the localeKeys, default value is ['zhCHS','zhCHT','en']
// example localeKeys: ['zhCHS','en','ja']
<div id="app">
<p>{{ $t(['ไฝ ๅฅฝ ไธ็','hello world','ใใใซใกใฏใไธ็']) }}</p>
</div>
use i18n option in component โ
export default {
i18n:{
en: {
message: {
hello: 'hello world'
}
},
zhCHS: {
message: {
hello: 'ไฝ ๅฅฝ ไธ็'
}
},
ja: {
message: {
hello: 'ใใใซใกใฏใไธ็'
}
}
},
setup(){
// code...
}
}
<div id="app">
<p>{{ $t('message.hello') }}</p>
</div>