Warning
The development of this module will continue at the repository @byjohann/vue-i18n under the scope @byjohann
.
Please migrate to the new package as this one will be deprecated soon.
Lightweight internationalization plugin for Vue.
- π Reactive locale messages β perfect for lazily added messages
- π Composable usage with
useI18n
- π― Global properties
$t
and$i18n
accessible in templates
# pnpm
pnpm add @leanera/vue-i18n
# npm
npm i @leanera/vue-i18n
To make use of @leanera/vue-i18n
in your components, initialize the i18n
instance:
// plugins/i18n.ts
import { createI18n } from '@leanera/vue-i18n'
const i18n = createI18n({
defaultLocale: 'en',
messages: {
en: {
intro: 'Welcome, {name}',
},
de: {
intro: 'Willkommen, {name}',
},
},
})
export default i18n
Inside your app's entry point, import the i18n
instance and add it you Vue:
// main.ts
import { createApp } from 'vue'
import i18n from './i18n'
const app = createApp(App)
app.use(i18n)
app.mount('#app')
Done! Now you can retrieve translated keys in your components:
const i18n = useI18n()
const { locale, t, setLocale } = i18n
locale.value // `en`
t('intro', { name: 'John' }) // `Welcome, John`
// Set new locale
setLocale('de')
locale.value // `de`
t('intro', { name: 'John' }) // `Willkommen, John`
const messages = {
en: {
intro: 'Hello World',
},
} | Template <p>{{ $t('intro') }}</p> Output <p>Hello World</p> |
const messages = {
en: {
intro: '{msg} World'
}
} | Template <p>{{ $t('intro', { msg: 'My' }) }}</p> Output <p>My World</p> |
const messages = {
en: {
intro: '{0} World',
},
} | Template <p>{{ $t('intro', ['My']) }}</p> Output <p>My World</p> List formatting also accepts array-like objects: Template <p>{{ $t('intro', {'0': 'My'}) }}</p> Output <p>My World</p> |
The properties $t
as well as $i18n
are available globally in your templates.
Example:
<p>{{ $t('intro') }}</p>
Instead of $t
and $i18n
you can import the useI18n
composable to access the current i18n instance. The useI18n
composable is available in the setup
hook (entry point for Composition API usage).
Types
function useI18n(): UseI18n
interface UseI18n {
defaultLocale: string
locale: ComputedRef<string>
locales: readonly string[]
messages: LocaleMessages
t: (key: string, params?: Record<string, any>) => string
setLocale: (locale: string) => void
getLocale: () => string
}
Example
import { useI18n } from '@leanera/vue-i18n'
const i18n = useI18n()
const {
defaultLocale,
locale,
locales,
messages,
t,
setLocale,
getLocale
} = i18n
console.log(defaultLocale === locale.value) // true
console.log(t('foo').value) // `bar`
- Clone this repository
- Enable Corepack using
corepack enable
- Install dependencies using
pnpm install
- Start development server using
pnpm run dev
insideplayground
MIT License Β© 2022-2023 LeanERA GmbH & Johann Schopplich