1、安装包vue-i18n
npm i vue-i18n --save
2、src 目录下新建locales目录,并在此目录下
- 新建index.js
import { createI18n } from 'vue-i18n'
const modules = import.meta.globEager('./*')
function getLangAll(): any {
let message: any = {}
getLangFiles(modules, message)
return message
}
function getLangFiles(mList: any, msg: any) {
for (let path in mList) {
if (mList[path].default) {
let pathName = path.substr(path.lastIndexOf('/') + 1, 5)
if (msg[pathName]) {
msg[pathName] = {
...mList[pathName],
...mList[path].default
}
} else {
msg[pathName] = mList[path].default
}
}
}
}
const i18n = createI18n({
legacy: false, // 使用Composition API,这里必须设置为false
globalInjection: true,
global: true,
locale: 'zh-CN',
fallbackLocale: 'zh-CN', // 默认语言
messages: getLangAll()
})
export default i18n
- 新建zh-CN.js,存放中文,例如
const Settings = {
settings: '设置',
search: '搜索',
airplaneMode: '飞行模式',
wlan: '无线局域网',
bluetooth: '蓝牙'
}
const Maps = {
searchPlaceHolder: '搜索地点或地址'
}
export default {
Settings,
Maps
}
- 新建en-US.js,存放英文,例如
const Settings = {
settings: 'Settings',
search: 'Search',
airplaneMode: 'Airplane Mode',
wlan: 'WLAN',
bluetooth: 'Bluetooth',
}
const Maps = {
searchPlaceHolder: 'search'
}
export default {
Settings,
Maps
}
3、在main.js中使用
import i18n from './locales/index'
app.use(i18n).mount('#app')
4、在页面template中使用
<div class="page-title">{{ $t("Settings.settings") }}</div>
5、通过按钮点击,全局切换语言
<template>
<button @click="changeLanguage">change language</button>
</template>
<script lang="ts">
import { defineComponent } from "vue";
import { useI18n } from "vue-i18n";
export default defineComponent({
name: "App",
components: {},
setup() {
const { locale } = useI18n({ useScope: "global" });
function changeLanguage() {
locale.value = "en-US";
}
return {
changeLanguage,
};
},
});
</script>