使用i18n国际化方案
- 创建单独国际化文件夹 locales
文件夹结构
locales ->
common -> 存放所有的语言文件
en.json
zh.json
index.ts -> 国际化方法封装
- 国际化index.ts文件
import type { App } from 'vue'
import { createI18n } from "vue-i18n";
import zh from './common/zh.json'
import en from './common/en.json'
const messages = {
en: { ...en },
zh: { ...zh }
}
export const getlang = () => {
const url = new URL(window.location as any)
let lang = url.searchParams.get('lang')
if (!lang) {
const langDefault = navigator?.languages[1] || 'zh'
lang = sessionStorage.getItem('lang') || langDefault
}
sessionStorage.setItem('lang', lang)
return lang
}
export const i18n = createI18n({
legacy: false,
globalInjection: true,
silentTranslationWarn: true,
silentFallbackWarn: true,
locale: getlang(),
fallbackLocale: 'zh',
messages,
})
export const $t: any = i18n.global.t
export const i18Key = (key: string) => key
export const initI18n = (app: App) => {
app.use(i18n)
}
- main.ts
import { createApp } from 'vue'
import App from './App.vue'
import { initRouter } from '@/router'
import { initPinia } from '@/stores'
import { initI18n } from '@/locales'
import './assets/main.css'
const app = createApp(App)
initPinia(app)
initI18n(app)
initRouter(app)
app.mount('#app')
- 组件中使用
<div>{{ $t('common.home') }}</div>
import { $t } from '@/locales'
$t('common.test')