筆記一下 PrimeVue 其語系要如何與 vue-i18n 進行連動。
內容
PrimeVue 在其官網的 Configuration -> Locale 環節有提及其套件有用到的翻譯清單,且告知可用 app.use 的方法來使用。
https://primevue.org/configuration/#locale
不過沒提及的是,其實是有 PrimeLocale 這個 repo 可以下載或透過 npm 安裝的。
由於我是搭配 Nuxt 進行使用,所以撰寫一個 plugin 來引入。語系對照表,你可以在該 plugin 內寫一個 map 來對應即可。
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
import enDict from 'primelocale/en.json' import zhTwDict from 'primelocale/zh-TW.json' import { usePrimeVue } from 'primevue/config' import { i18n, LocaleMap } from '@/plugins/lang' const langDictMap = { [LocaleMap.zhTw]: zhTwDict['zh-TW'], [LocaleMap.enUs]: enDict['en'], } export default defineNuxtPlugin(() => { const initialLocale = i18n.global.locale.value const langDict = langDictMap[initialLocale] ?? enDict['en'] const primeVue = usePrimeVue() primeVue.config.locale = langDict }) |
對應的 vue-i18n plugin
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
import { createI18n } from 'vue-i18n' import enUsLocale from '~~/lang/en-us' import zhTwLocale from '~~/lang/zh-tw' export enum LocaleMap { zhTw = 'zh-tw', enUs = 'en-us', } export enum ogTitleLocaleMap { zhTw = 'zh-TW', enUs = 'en-US', } export type LocaleMapType = (typeof LocaleMap)[keyof typeof LocaleMap] export const messages = { [LocaleMap.zhTw]: { ...zhTwLocale, }, [LocaleMap.enUs]: { ...enUsLocale, }, } export const appLangs = Object.keys(messages) export type appLangType = keyof typeof messages export const i18n = createI18n({ legacy: false, locale: LocaleMap.zhTw, globalInjection: true, fallbackLocale: LocaleMap.zhTw, messages, }) export default defineNuxtPlugin(({ vueApp }) => { vueApp.use(i18n) }) |
參考資料
1. primefaces/primelocale
2. PrimeVue Configuration

