首先安裝庫:
npm i vue-i18n@next
npm i vue-cli-plugin-i18n@next
vite.config.ts 配置:
import {defineConfig} from "vite"
import vue from "@vitejs/plugin-vue"
import path from 'path'
import {vueI18n} from "@intlify/vite-plugin-vue-i18n"
// https://vitejs.dev/config/
export default defineConfig({
resolve: {
alias: {
'vue-i18n': 'vue-i18n/dist/vue-i18n.runtime.esm-bundler.js'
}
},
plugins: [
vue(),
vueI18n(
{
include: path.resolve(__dirname, './src/i18n/locales/**')
}
)
// ... 這里是其他配置
]
})
src 目錄新增 i18n文件夾瞎嬉,i18n文件夾下新建 index.ts文件和 locales 文件夾
import { createI18n } from 'vue-i18n'
import enUS from './locales/en-US.json'
import zhCN from './locales/zh-CN.json'
type MessageSchema = typeof enUS
const i18n = createI18n<[MessageSchema], 'en-US' | 'zh-CN'>({
// 默認(rèn)語言先取自定義的,再取瀏覽器的膝宁,最后默認(rèn)英文
locale: localStorage.getItem("locale") || navigator.language || 'en-US',
legacy: false,
// allowComposition: true, // 是否允許在 Legacy API 模式下使用 Composition API
messages: {
'en-US': enUS,
'zh-CN': zhCN // 可以追加其他語言
}
})
export default i18n
locales 文件夾下新建 zh-CN.json短曾、en-US.json
文件內(nèi)格式要保持一樣:
舉例:
zh-CN.json
{
"Home": "首頁"
}
en-US.json
{
"Home": "Home"
}
然后在 main.ts 安裝插件:
import i18n from './i18n'
...
// 國際化管理
app.use(i18n)
接著就能在vue組件中使用了,使用方式是:
<script setup lang="ts">
import i18n from "./i18n"
const setLanguage = (locale: 'zh-CN' | 'en-US') => {
// @ts-ignore, 這是官方的錯誤抗果,本身現(xiàn)在它就是一個ComputedRefImpl類型的參數(shù)
if(locale !== i18n.global.locale.value) {
localStorage.setItem("locale", locale)
// @ts-ignore
i18n.global.locale.value = locale
// 重新加載頁面,組件的類型才能生效
location.reload()
return true // 這里加彈窗也可以
}{
return false
}
}
</script>
<template>
<h1>{{ $t('Home') }}</h1>
<button @click="setLanguage('zh-CN')">簡體中文</button>
</template>
setLanguage方法可以抽離出來放到utils目錄中的index里面單獨導(dǎo)出奸晴,后續(xù)作為標(biāo)準(zhǔn)工具冤馏。
下一篇文章說說 NaiveUI全局組件語言的變更。