Vue3 must use version 9.* when using i18n
"vue-i18n": "^9.2.2"
Table of contents
1.3, there will be a warning at this time
3.1, Linked messages (associated information)
3.2, Built-in Modifiers (built-in modifiers)
3.4, HTML messages (HTML information)
4. Pluralization (diversification)
1. Download and use
npm
npm install vue-i18n@9
yarn
yarn add vue-i18n@9
lang
1.1. Create configuration
Create the lang folder, and then create cn.ts, en.ts and the most important index.ts inside
cn.ts
const messages = {
home: {
title: '书城',
hint: '计算机科学和软件工程',
guessYouLike: '猜你喜欢'
}
}
export default messages
a.ts
const messages = {
home: {
title: 'Book Store',
hint: 'Computer Science And Software Engineering',
guessYouLike: 'Guess You Like',
}
}
export default messages
index.ts
import { createI18n } from 'vue-i18n'
import en from './en'
import cn from './cn'
//引入的不同语言文件
const messages = {
en, cn
}
//这个类型可以自己配置,毕竟每个人做的都不一样
const i18n:any =createI18n( {
legacy: false, // 使用 Composition API 模式,则需要将其设置为false
globalInjection: true, //全局生效$t
locale: 'cn', // 默认cn翻译
messages //ES6解构
})
export default i18n;
If you want to configure other files, you can add
vue main.ts
import { createApp } from 'vue'
import App from './App.vue'
import i18n from './lang/index.js'
const app = createApp(App)
app.use(i18n);
app.mount('#app')
1.2. Basic usage
On any component, it is the same as shown in the following
Use parameters:
- path: required, the key of locale information
- locale: optional, locale (this has been configured in 1.1 and can be modified by pinia or storage)
- args: optional, for list or named format (said in 2.0)
<template>
//使用 $t
<span> {
{ $t("home.title") }} </span>
//使用 t (要解构)
<p>{
{t("home.title")}}</p>
//使用v-t , 这个数据是没有的,只是用来展示如何使用v-t
<p v-t="{path:'title',args: {count: 10 }}"></p>
//使用翻译组件
// keypath:必传,和上面path参数一样 tag:可选,转为什么标签
// locale:可选,要用哪个语言环境 scope:可选,全局还是局部 `global` or `parent`
// i18n:可选,优先级比scope高,参数也多,用的也不多,就不介绍了
<i18n-t keypath='home.title' tag="p" locale='en' scope="global"></i18n-t>
</template>
<script setup lang='ts'>
import { useI18n } from 'vue-i18n'
const { t } = useI18n()
</script>
<style lang='less' scoped></style>
1.3, there will be a warning at this time
警告:You are running the esm-bundler build of vue-i18n. It is recommended to configure your bundler to explicitly replace feature flag globals with boolean literals to get proper tree-shaking in the final bundle.
Install
npm install @intlify/vite-plugin-vue-i18n
vite.config.ts
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import vueI18n from '@intlify/vite-plugin-vue-i18n'
//引入resolve
import { resolve } from 'path'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [vue(),
//配置vueI18n
vueI18n({
include: resolve(__dirname, './path/to/src/locales/**')
})]
})
Warning solution comes from Star House
2. Interpolation
Only modify the cn.ts file below
2.1, named interpolation
define interpolation
const messages = {
home: {
title: `书城{a}{b}`,
}
}
export default messages
use
<template>
<p>
{
{ $t("home.title", {a:'123',b:'9999'}) }}
</p>
</template>
Effect
2.2. List interpolation
define interpolation
const messages = {
home: {
title: `书城{0}{1}`,
hint: '计算机科学和软件工程{0}',
guessYouLike: '猜你喜欢'
}
}
export default messages
List interpolation defines the mustache syntax sequence starting from 0,
Note: When used, the subscript of the array corresponds to the list value in its {} brackets
use
<template>
<p>
{
{ $t("home.title", ['一二','四五六']) }}
</p>
<p>
{
{ $t("home.hint", ['123']) }}
</p>
</template>
Effect
2.3, text interpolation
Literal interpolation is mainly useful for special characters in message format syntax,
Example: { } @ $ |
These are not available directly in the message.
Definition format: {' X '} Use quotes in brackets
const messages = {
home: {
title: `书城{'{'}这是一个书城{'}'}`,
}
}
export default messages
If you use title directly like this: `Book City{This is a Book City}`, it will report an error
Translation: Message Compilation error: Invalid token in placeholder 'This is a bookstore'
3、messages
3.1, Linked messages (associated information)
Role: put different values together
Format: @:key
//定义 ,这不是cn.ts文件的只是修改下,把代码减少
export default {
book:'流浪地球',
author:'刘慈欣',
cover: "@:book - @:author",
}
//使用
<template>
<p>
{
{ $t("cover", ) }}
</p>
</template>
3.2, Built-in Modifiers (built-in modifiers)
Format: @.modifier:key
upper: capitalizes all characters in the link message
lower: capitalizes all characters in the link message
capitalize: capitalizes the first character in the link message
export default {
homeAddress: 'Home address',
upper: '@.upper:homeAddress'
}
<template>
<p>{
{ $t('homeAddress') }}</p>
<p>{
{ $t('upper') }}</p>
</template>
3.3. Custom modifiers
const i18n:any =createI18n( {
locale: 'cn', // 默认cn翻译
messages,
// 在' modifiers '选项设置自定义修饰符
modifiers: {
//别问为什么是any,问就是不知道怎么解决
snakeCase: (str:any) => str.split(' ').join('_')
}
})
The use is also the same as that of 3.2
export default {
homeAddress: 'Home address',
upper: '@.snakeCase:homeAddress'
}
3.4, HTML messages (HTML information)
You can also use html tags, and then use v-html to parse, but the requirements of v-html should be clear to yourself
//定义
export default {
cover:'hello <br> world'
}
//使用
<template>
<p v-html="$t('cover')"></p>
</template>
4. Pluralization (diversification)
export default {
car: 'car | cars',
apple: 'no apples | one apple | {count} apples'
}
//使用------
<template>
<p>{
{ $t('car', 1) }}</p>
<p>{
{ $t('car', 2) }}</p>
<p>{
{ $t('apple', 0) }}</p>
<p v-t="{ path: 'apple',args: 2 }"></p>
<p>{
{ t('apple', 1) }}</p>
<p>{
{ $t('apple', 10, { count: 10 }) }}</p>
// plural:必传,9.2.2的预期不够好,不能绑定对象,只能绑定值
<i18n-t keypath="message.plural" :plural="n">
//要给传的复数,并且还要写值下来,就算是唯一一个值也要写,不然就是空
<template #count> {
{ n }} </template>
</i18n-t>
</template>
<script setup lang='ts'>
import { ref } from 'vue';
import { useI18n } from 'vue-i18n'
const { t } = useI18n()
const n= ref(4)
</script>
//结果------
<p>car</p>
<p>cars</p>
<p>no apples</p>
<p>2 les</p>
<p>one apple</p>
<p>10 les</p>
<p>4 les</p>
Some methods that support diversification are: In addition to $tc shown above
1. $tc (only valid for legacy set to true, don't mind using it )
2. vt custom command (customized by i18n, see 1.2 basic usage)
3. Built-in translation component (i18n-t) (currently not recommended, more troublesome)
4. Use deconstruction t to use i18n
5. Inject global $t,
predefined implicit parameters
Implicit parameters refer to the second parameter of (key value, implicit parameter, {xxx:x}), and the third is the display parameter.
The implicit parameter can specify the second defined value, but its priority is not as high as the third parameter,
for example:
//定义 export default { apple: 'no apples | one apple | {count} les | { count } apples ' } //使用 <template> <p>{ { $t('apple', 0) }}</p> //结果 no apples <p>{ { $t('apple', 1) }}</p> //结果 one apple <p>{ { $t('apple', 2) }}</p> //结果 2 les <p>{ { $t('apple', 3) }}</p> //结果 3 les <p>{ { $t('apple', 4, { count: 10 }) }}</p> //结果 4 les </template>
The last line did not get the effect I expected. It is probably a bug. After all, this has been changing and has not really stabilized.
My expectation is 10 apples but i don't know where it will go
Multiple plural definitions, to be customized , otherwise only the first plural will be displayed
Custom specific look: vue-i18n official website
Chinese website (not the official website, the version is 8.*, there is a certain reference): Vue I18n v8.x manual