4 changed files with 36 additions and 49 deletions
@ -1,47 +0,0 @@ |
|||
import { watchEffect, DirectiveBinding } from 'vue' |
|||
import { useStore } from '@/store' |
|||
import { chineseLanguageLoader } from '@/i18n/util' |
|||
|
|||
interface MyHtmlElement extends HTMLElement { |
|||
stopHandler: (() => void) | null |
|||
} |
|||
|
|||
/* |
|||
ep:v-language:title="state.obj" |
|||
*/ |
|||
|
|||
export default { |
|||
mounted(el: MyHtmlElement, binding: DirectiveBinding) { |
|||
if (el.stopHandler) { |
|||
el.stopHandler() |
|||
el.stopHandler = null |
|||
} |
|||
el.stopHandler = watchEffect(() => { |
|||
const store = useStore() |
|||
const language = store.language |
|||
const { arg, value } = binding |
|||
|
|||
if (!Object.keys(value)?.length || !arg) { |
|||
return '' |
|||
} |
|||
|
|||
let content = '' |
|||
if (language === 'zh') { |
|||
content = value[arg] |
|||
} |
|||
if (language === 'en' && value[arg + 'En']) { |
|||
content = value[arg + 'En'] |
|||
} else if (language === 'en' && !value[arg + 'En']) { |
|||
content = value[arg] |
|||
} |
|||
if (language === 'tw') { |
|||
content = chineseLanguageLoader(value[arg]) |
|||
} |
|||
el.innerHTML = content |
|||
}) |
|||
}, |
|||
beforeUnmount(el: MyHtmlElement) { |
|||
el.stopHandler && el.stopHandler() |
|||
el.stopHandler = null |
|||
} |
|||
} |
|||
@ -0,0 +1,26 @@ |
|||
import { useStore } from '@/store' |
|||
import type { App } from 'vue' |
|||
import { chineseLanguageLoader } from '@/i18n/util' |
|||
|
|||
export const switchLanguage = { |
|||
install: (app: App<Element>) => { |
|||
const store = useStore() |
|||
|
|||
app.config.globalProperties.switchLanguage = <V extends object, K extends keyof V>(value: V, key: K): V[K] => { |
|||
const language = store.language |
|||
let content: any |
|||
if (language === 'zh') { |
|||
content = value[key] |
|||
} |
|||
if (language === 'en' && value[(key + 'En') as keyof typeof value]) { |
|||
content = value[(key + 'En') as keyof typeof value] |
|||
} else if (language === 'en' && !value[(key + 'En') as keyof typeof value]) { |
|||
content = value[key] |
|||
} |
|||
if (language === 'tw') { |
|||
content = chineseLanguageLoader(value[key]) |
|||
} |
|||
return content |
|||
} |
|||
} |
|||
} |
|||
@ -0,0 +1,7 @@ |
|||
declare module '@vue/runtime-core' { |
|||
export interface ComponentCustomProperties { |
|||
// eslint-disable-next-line no-unused-vars
|
|||
switchLanguage: <V extends object, K extends keyof V>(value: V, key: K) => V[K] |
|||
} |
|||
} |
|||
export {} |
|||
Loading…
Reference in new issue