Skip to content

Instantly share code, notes, and snippets.

@hipertracker
Last active May 14, 2021 09:54
Show Gist options
  • Save hipertracker/14ec974242ca85789ad8b1be2e6e46cb to your computer and use it in GitHub Desktop.
Save hipertracker/14ec974242ca85789ad8b1be2e6e46cb to your computer and use it in GitHub Desktop.
Quasar2 + Vue3 + TypeScript - locale switcher component
<template>
<q-btn-dropdown :label="locale" dense flat>
<q-list
v-for="(label, loc) in allowedLocales"
:key="loc"
:class="bgTheme"
dense
>
<q-item
v-close-popup
:clickable="locale !== loc"
tabindex="0"
@click="changeLocale(loc)"
>
<q-item-section side>
{{ label }}
</q-item-section>
<q-item-section v-show="locale === loc">
<q-icon name="keyboard_arrow_left" />
</q-item-section>
</q-item>
</q-list>
</q-btn-dropdown>
</template>
<script lang="ts">
import fp from 'lodash/fp';
import { defineComponent, onMounted, computed } from 'vue';
import { useI18n } from 'vue-i18n';
import { useQuasar } from 'quasar';
import { useRoute } from 'vue-router';
export default defineComponent({
name: 'LocaleSwitcher',
setup() {
const { locale } = useI18n({ useScope: 'global' });
const $q = useQuasar();
const route = useRoute();
const allowedLocales = {
en: 'English',
pl: 'Polski',
// add more...
};
const bgTheme = computed(() => {
return $q.dark.isActive ? 'bg-grey-10' : 'bg-white';
});
onMounted(() => {
const defaultLang = 'en';
const allowed = Object.keys(allowedLocales);
const browserLocale = $q.lang.getLocale()?.split('-')[0] || defaultLang;
const cachedLocale = $q.localStorage.getItem('locale');
const lang = route.query.locale || cachedLocale || browserLocale;
if (fp.includes(lang as string)(allowed)) {
const val = lang as string;
if (locale.value !== val) {
locale.value = val;
}
if (cachedLocale !== val) {
$q.localStorage.set('locale', val);
}
}
});
function changeLocale(lang: string) {
locale.value = lang;
$q.localStorage.set('locale', lang);
}
return {
allowedLocales,
bgTheme,
changeLocale,
locale,
};
},
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment