fix: make i18n reactive to language changes
This commit is contained in:
+12
-7
@@ -1,14 +1,9 @@
|
|||||||
// src/renderer/src/i18n/index.ts
|
// src/i18n/index.ts
|
||||||
import { ref, computed } from 'vue'
|
import { ref, computed, watch } from 'vue'
|
||||||
import en from './locales/en'
|
import en from './locales/en'
|
||||||
import zhCN from './locales/zh-CN'
|
import zhCN from './locales/zh-CN'
|
||||||
|
|
||||||
type Messages = typeof en
|
type Messages = typeof en
|
||||||
type NestedKeyOf<T> = {
|
|
||||||
[K in keyof T & string]: T[K] extends object
|
|
||||||
? `${K}.${NestedKeyOf<T[K]>}`
|
|
||||||
: K
|
|
||||||
}[keyof T & string]
|
|
||||||
|
|
||||||
const messages: Record<string, Messages> = {
|
const messages: Record<string, Messages> = {
|
||||||
en,
|
en,
|
||||||
@@ -19,6 +14,13 @@ const currentLocale = ref<string>(
|
|||||||
localStorage.getItem('locale') || 'zh-CN'
|
localStorage.getItem('locale') || 'zh-CN'
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// Force re-render trigger
|
||||||
|
const localeVersion = ref(0)
|
||||||
|
|
||||||
|
watch(currentLocale, () => {
|
||||||
|
localeVersion.value++
|
||||||
|
})
|
||||||
|
|
||||||
export function useI18n() {
|
export function useI18n() {
|
||||||
const locale = computed({
|
const locale = computed({
|
||||||
get: () => currentLocale.value,
|
get: () => currentLocale.value,
|
||||||
@@ -29,6 +31,9 @@ export function useI18n() {
|
|||||||
})
|
})
|
||||||
|
|
||||||
function t(path: string, params?: Record<string, string | number>): string {
|
function t(path: string, params?: Record<string, string | number>): string {
|
||||||
|
// Access localeVersion to make t() reactive
|
||||||
|
void localeVersion.value
|
||||||
|
|
||||||
const keys = path.split('.')
|
const keys = path.split('.')
|
||||||
let result: any = messages[currentLocale.value] || messages.en
|
let result: any = messages[currentLocale.value] || messages.en
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user