1、安装vue-i18n
我目前使用的版本"vue": “^3.2.25”, “vue-i18n”: “^9.1.10”,
pnpm i vue-i18n
2、新建中英文对照语言
// language/en.js
export default {
菜单:'menu',
title:'title'
}
// language/zh-cn.js
export default {
菜单:'菜单',
title:'标题'
}
// language/index.js
import zhCn from "./zh-cn";
import en from "./en";
const language = {
'zh-CN':zhCn,
'en-US':en
}
export default language
3、在main.js中引入
// main.js
import { createI18n } from 'vue-i18n'
import language from './language'
const international = createI18n({
//名字要和上面的一致
locale:'zh-CN',
messages:language
})
const app = createApp(App)
// 使用国际化
app.use(international)
4、切换语言
<script setup>
import { getCurrentInstance } from "vue";
import { useI18n } from 'vue-i18n'
// 切换语言
const { proxy } = getCurrentInstance() as any;
const $t = useI18n()
const changeLanguage = (type: String) => {
console.log("当前选择的语言:" + type);
switch (type) {
case "chinese":
proxy.$i18n.locale = "zh-CN";
break;
case "english":
proxy.$i18n.locale = "en-US";
break;
}
console.log(proxy);
};
</script>
<template>
<!-- 切换语言 -->
<h1>{{ $t('title') }}</h1>
<h1>{{ $t('菜单') }}</h1>
<button @click="changeLanguage('chinese')">中文</button>
<button @click="changeLanguage('english')">英文</button>
</template>
ok!!!
大功告成了,快去试试吧