mirror of
https://github.com/m1k1o/neko.git
synced 2025-04-29 18:36:22 +02:00
feat(i18n): enhance language management by saving user preference and auto detect browser language (#487)
* feat(i18n): enhance language management by saving user preference and detecting browser language - Added a watcher to save the selected language to localStorage on change. - Implemented browser language detection to set the default language based on user settings or browser preferences. * use ~/utils/localstorage, remove setting savedLang in mounted as this is already set in i18.ts. * do not repeat fallbackLocale and remove console log. --------- Co-authored-by: Miroslav Šedivý <sedivy.miro@gmail.com>
This commit is contained in:
parent
4e335efb1e
commit
212bf8a607
2 changed files with 29 additions and 3 deletions
|
@ -60,8 +60,9 @@
|
|||
</style>
|
||||
|
||||
<script lang="ts">
|
||||
import { Component, Vue } from 'vue-property-decorator'
|
||||
import { Component, Vue, Watch } from 'vue-property-decorator'
|
||||
import { messages } from '~/locale'
|
||||
import { set } from '~/utils/localstorage'
|
||||
|
||||
@Component({ name: 'neko-menu' })
|
||||
export default class extends Vue {
|
||||
|
@ -77,6 +78,11 @@
|
|||
this.$accessor.client.toggleAbout()
|
||||
}
|
||||
|
||||
@Watch('$i18n.locale')
|
||||
onLanguageChange(newLang: string) {
|
||||
set('lang', newLang)
|
||||
}
|
||||
|
||||
mounted() {
|
||||
const default_lang = new URL(location.href).searchParams.get('lang')
|
||||
if (default_lang && this.langs.includes(default_lang)) {
|
||||
|
|
|
@ -1,11 +1,31 @@
|
|||
import Vue from 'vue'
|
||||
import VueI18n from 'vue-i18n'
|
||||
import { messages } from '~/locale'
|
||||
import { get } from '~/utils/localstorage'
|
||||
|
||||
Vue.use(VueI18n)
|
||||
|
||||
const fallbackLocale = 'en'
|
||||
|
||||
function detectBrowserLanguage(): string {
|
||||
const browserLang = navigator.language.toLowerCase()
|
||||
|
||||
const supportedLangs = Object.keys(messages)
|
||||
if (supportedLangs.includes(browserLang)) {
|
||||
return browserLang
|
||||
}
|
||||
|
||||
const baseLang = browserLang.split('-')[0]
|
||||
const matchingLang = supportedLangs.find((lang) => lang.startsWith(baseLang))
|
||||
if (matchingLang) {
|
||||
return matchingLang
|
||||
}
|
||||
|
||||
return fallbackLocale
|
||||
}
|
||||
|
||||
export const i18n = new VueI18n({
|
||||
locale: 'en',
|
||||
fallbackLocale: 'en',
|
||||
locale: get<string>('lang', detectBrowserLanguage()),
|
||||
fallbackLocale,
|
||||
messages,
|
||||
})
|
||||
|
|
Loading…
Add table
Reference in a new issue