一. 安装类库
npm install vue-i18n@next
@next 表示安装i18n 最新的 vue3的版本文章来源:https://www.toymoban.com/news/detail-566453.html
二. 配置 i18n的 配置文件
// i18n.ts
import { createI18n } from 'vue-i18n'
import zh from './zh'
import en from './en'
const i18n = createI18n({
legacy: false, // 没有该参数可能会报错
locale: 'zh',
messages: {
zh,
en
}
})
export default i18n
// zh.ts
export default {
message: {
homeText: '主页',
mineText: '个人中心'
}
}
三. 挂载到实例上
// main.ts
import i18n from './language/i18n'
const app = createApp(App)
...
app.use(i18n)
四. 使用
// 使用的 xxx.vue
<script setup lang="ts">
import { useI18n } from "vue-i18n";
const { t } = useI18n()
</script>
<template>
<p>{{t('message.homeText') }} </p>
</template>
点击按钮切换语言 文章来源地址https://www.toymoban.com/news/detail-566453.html
<script setup lang="ts">
import { useI18n } from 'vue-i18n'
// 核心思想就是改变 useI18n 解构出来的locale
// 笔者 这里为了和页面中的其他变量 区别 - 取别名 i18nLanguage。
const { locale: i18nLanguage } = useI18n()
const toggle = (languageKey) => {
i18nLanguage.value = languageKey // zh en
}
</script>
<template>
<el-button @click="toggle('zh')">点击切换中文</el-button>
<el-button @click="toggle('en')">点击切换英文</el-button>
</template>
到了这里,关于vue3 i18n配置详细教学的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!