开始安装
pnpm add i18next i18next-vue i18next-browser-languagedetector
建立i18n文件
import i18next from 'i18next'
import I18NextVue from 'i18next-vue'
import LanguageDetector from 'i18next-browser-languagedetector'
import {App} from 'vue'
import en from './en.ts'
import zh_cn from './zh_cn.ts'
i18next
// detect user language
// learn more: https://github.com/i18next/i18next-browser-languageDetector
.use(LanguageDetector)
// init i18next
// for all options read: https://www.i18next.com/overview/configuration-options
.init({
debug: true,
fallbackLng: 'en',
resources: {
en: {
translation: en
},
"zh-CN":{
translation: zh_cn
}
}
});
export default {
install(app:App) {
app.use(I18NextVue, { i18next })
}
}
建立zh_cn.ts
export default {
name:"你好世界"
}
入口文件main.ts
修改
import {createApp} from 'vue'
import router from './router'
import 'virtual:uno.css'
import App from './App.vue'
import i18n from './i18n'
createApp(App).use(router).use(i18n).mount('#app')
app.vue
<script setup lang="ts">
import i18next from 'i18next'
import {ref} from 'vue'
const lng = ref(i18next.language)
const change = () => {
i18next.changeLanguage(lng.value)
}
</script>
<template>
<div>
<button>{{ $t("name" as any) }}</button>
<div class="flex">
<div class="h-[30px]">
<select v-model="lng" @change="change()">
<option value="en">english</option>
<option value="zh-CN">中文</option>
</select>
</div>
</div>
</div>
</template>
<style scoped>
</style>