Files
blog/frontend/app/components/LanguageSwitcher.vue
T
davide c08f53ca69 Add a language switcher with English, Italian, Spanish and French
The interface is translated through @nuxtjs/i18n: strings live in
i18n/locales/*.json, routes are prefixed except for the default English, and
useLocaleHead emits the lang attribute, the hreflang alternates and og:locale.

The switcher is a native select rather than a custom dropdown: keyboard
support, the platform picker on mobile and correct labelling come for free.

Article content stays single-language — this translates the site chrome only.
2026-08-25 14:23:09 +02:00

72 lines
1.6 KiB
Vue

<script setup lang="ts">
const { locale, locales, t } = useI18n()
const switchLocalePath = useSwitchLocalePath()
const router = useRouter()
/**
* A native select: it gets keyboard support, the platform picker on mobile and
* correct labelling for free, which a hand-built dropdown would have to rebuild.
*/
function onChange(event: Event) {
const code = (event.target as HTMLSelectElement).value as typeof locale.value
const path = switchLocalePath(code)
if (path) router.push(path)
}
</script>
<template>
<div class="switcher">
<label class="visually-hidden" for="locale-select">{{ t('site.languageLabel') }}</label>
<select id="locale-select" :value="locale" @change="onChange">
<option v-for="option in locales" :key="option.code" :value="option.code">
{{ option.name }}
</option>
</select>
<span class="arrow" aria-hidden="true"></span>
</div>
</template>
<style scoped>
.switcher {
position: relative;
display: inline-flex;
align-items: center;
}
select {
appearance: none;
padding: 0.35rem 1.6rem 0.35rem 0.7rem;
border: 1px solid var(--color-border);
border-radius: 0;
background: transparent;
color: var(--color-body);
font: inherit;
font-size: 0.75rem;
font-weight: 600;
letter-spacing: 0.14em;
text-transform: uppercase;
cursor: pointer;
}
select:hover {
border-color: var(--color-ink);
color: var(--color-ink);
}
.arrow {
position: absolute;
right: 0.6rem;
font-size: 0.65rem;
pointer-events: none;
}
.visually-hidden {
position: absolute;
width: 1px;
height: 1px;
overflow: hidden;
clip-path: inset(50%);
white-space: nowrap;
}
</style>