Last active
November 21, 2021 01:52
-
-
Save xiCO2k/423cc14884955363efac54053686c62c to your computer and use it in GitHub Desktop.
Simple Localization Script to sue with vue3 and Laravel
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { reactive } from 'vue'; | |
import axios from 'axios'; | |
const reactiveMessages = reactive({}); | |
const loaded = []; | |
function setI18nLanguage(locale) { | |
axios.defaults.headers.common['Accept-Language'] = locale; | |
document.querySelector('html').setAttribute('lang', locale); | |
const { messages } = loaded.find(({ lang }) => lang === locale); | |
for (const [key, value] of Object.entries(messages)) { | |
reactiveMessages[key] = value; | |
} | |
for (const [key] of Object.entries(reactiveMessages)) { | |
if (! messages[key]) { | |
reactiveMessages[key] = null; | |
} | |
} | |
return locale; | |
} | |
export const defaultLocale = document.documentElement.lang || 'en'; | |
export function loadLanguageAsync(lang = defaultLocale) { | |
if (loaded.includes(lang)) { | |
return Promise.resolve(setI18nLanguage(lang)); | |
} | |
return import(`../lang/${lang}.json`).then(({ default: messages }) => { | |
loaded.push({ lang, messages }); | |
return setI18nLanguage(lang); | |
}); | |
} | |
export function trans(key, values) { | |
if (! reactiveMessages[key]) { | |
reactiveMessages[key] = key; | |
} | |
let message = reactiveMessages[key]; | |
const capitalize = s => s.charAt(0).toUpperCase() + s.slice(1); | |
Object.entries(values || []).forEach(([key, value]) => { | |
value = '' + value; | |
message = message | |
.replace(`:${key}`, value) | |
.replace(`:${key.toUpperCase()}`, value.toUpperCase()) | |
.replace(`:${capitalize(key)}`, capitalize(value)); | |
}); | |
return message; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment