# vue3 中使用 i18n
# 1. 介绍
vue3 + TS,使用 i18n
# 2. 快速开始
安装:
npm i vue-i18n
# "vue-i18n": "^9.13.1",
引入:
main.ts
import { createApp } from 'vue'; import { i18n } from './i18n'; import App from './App.vue'; createApp(App) .use(i18n) .mount('#app');
./i18n.ts
import { createI18n } from 'vue-i18n'; import en from './en'; import zh from './zh'; export const i18n = createI18n({ locale: 'en', // set current locale messages: { en, zh, }, });
./en.ts
export default { FORM_INPUT_ERROR_REQUIRED: 'Required', };
./zh.ts
export default { FORM_INPUT_ERROR_REQUIRED: '必填', };
在模板中使用:
<template>
<div>{{ $t('FORM_INPUT_ERROR_REQUIRED') }}</div>
<div>{{ message }}</div>
</template>
<script>
export default {
data() {
return {
message: this.$t('FORM_INPUT_ERROR_REQUIRED'),
};
},
}
</script>
在 TS 文件中使用:
import { i18n } from './i18n';
console.log(i18n.global.t('FORM_INPUT_ERROR_REQUIRED'));
占位符:
const messages = {
en: {
hello: 'hello, {name} !',
hobbies: '{0}, {1}'
}
}
<p>{{ $t('hello', { name: '张三' }) }}</p>
<p>{{ $t('hobbies', ['football', 'basketball']) }}</p>
# 3. 切换语言
# 3.1. 在组件内切换
<template>
<select v-model="$i18n.locale">
<option
v-for="locale in $i18n.availableLocales"
:key="`locale-${locale}`"
:value="locale"
>
{{ locale }}
</option>
</select>
</template>
# 3.2. 在代码中切换
const i18n = createI18n({ /* ... */ });
i18n.global.locale = 'en';
# 4. 参考
上一篇: 下一篇:
本章目录