vue-i18n-composable

2.0.0 · active · verified Sun Apr 19

vue-i18n-composable is a library that brings the Composition API pattern for internationalization (i18n) to Vue 2.x applications, specifically integrating with the popular `vue-i18n` library. Its current stable version is `2.0.0`, released in July 2022, which introduced direct support for Vue 2.7 without requiring the `@vue/composition-api` plugin. Previous versions, such as `v1.0.0`, targeted Vue 2.5 and 2.6 and necessitated the `@vue/composition-api` plugin. The package does not adhere to a strict time-based release cadence, with major versions often tied to critical Vue lifecycle updates or feature enhancements. It differentiates itself by allowing developers to leverage modern `setup` functions and `useI18n` composables within Vue 2 projects, offering a forward-looking development experience without the need for a full migration to Vue 3. This is particularly useful for large legacy Vue 2 applications aiming to incrementally modernize their codebase, and it is an official part of the Intlify ecosystem, which also maintains `vue-i18n` itself.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates initializing `vue-i18n-composable` with `createI18n` and using `useI18n` within a Vue 2.7 `defineComponent` setup function to display translated text and change locales dynamically.

import Vue from 'vue'
import { createI18n } from 'vue-i18n-composable'
import { defineComponent } from 'vue' // For Vue 2.7+

const i18n = createI18n({
  locale: 'en',
  messages: {
    en: {
      greeting: 'Hello from Composition API!',
      language: 'English'
    },
    ja: {
      greeting: 'コンポジションAPIからのこんにちは!',
      language: '日本語'
    }
  }
})

const App = defineComponent({
  template: `
    <div>
      <h1>{{ t('greeting') }}</h1>
      <p>Current Language: {{ t('language') }}</p>
      <button @click="setLocale('ja')">Switch to Japanese</button>
      <button @click="setLocale('en')">Switch to English</button>
    </div>
  `,
  setup() {
    const { t, locale } = useI18n()

    const setLocale = (lang) => {
      locale.value = lang
    }

    return {
      t,
      setLocale
    }
  }
})

const app = new Vue({
  render: h => h(App),
  i18n
})

app.$mount('#app')

view raw JSON →