Giter Club home page Giter Club logo

debbie-vuex-i18n's Introduction

Debbie Vuex i18n

A simple Localization tool for Vuex/Vue (3)

I created it while developing with Laravel and was facing the problem, that I do not want load all translations at once.

This is an experimental version and not indented for production usage yet.

Overview



Content

Installation


npm i -D @gelbehexe/debbie-vuex-i18n

Usage by Example

Contextual language loader (optional)

This is only required if you want to use contextual loading.

Create a language loader function e.g. lib/languageLoader.js

function languageLoader(contexts) {
    return new Promise(function (resolve, reject) { 
        axios.get("/api/localization-context",{
            params: {
                contexts
            }
        }).resolve(data => {
            resolve(data)
        }).catch(err => reject(err))
    })
}

Initialization


In your main script e.g. app.js

import { createApp } from 'vue'
import App from './App.vue'

import store from "@/lib/store"; // your configured storage
import { translationPlugin } from "@gelbehexe/debbie-vuex-i18n"

// required only for contextual language loading
import languageLoader from "@/lib/languageLoader";

const app = createApp(App)

app.use(store)

// add plugin to app
app.use(translationPlugin, {
    store,
    languageLoader,
    // your localization languages
    locale: {
        current: "de",
        fallback: "en",
    },
    // Initial translations
    // - for fallback locale only the keys
    //   which are not set in default language 
    //   are needed
    translations: {
        en: {
            en1: "English Only",
        },
        de: {
            key1: "Deutsch 1",
            key2: "Deutsch 2",
            en_de: "Englisch und Deutsch"
        }
    }
})


app.mount('#app')

Usage in templates

Inner component
<templatep>
  <div>
    <h1>{{ t("key1") }}</h1>
    <p>{{ t("context1.key1"}}</p>
  </div>
</templatep>

<script>
import store from "@/lib/store"; // your configured storage
import { useTranslation } from "@gelbehexe/debbie-vuex-i18n"

export default {
  name: "MyComponent",
  setup() {
    const { t, addDeferredLocalizationContext } = useTranslation(store)
    addDeferredLocalizationContext("context1")
    
    return {
      t
    }
  }
}
</script>

Outermost component

Use v-vuex-translation directive to trigger previously deferred context loading. You can use it without a value or with a method which is called after loading.

Important: For a dynamic update after contextual loading it is necessary that the context is rendered.

<template>
  <div v-vuex-translation="handleTranslationLoaded">
    <div v-if="loading">Loading ...</div>
    <!-- Important do not use v-else here -->
    <div v-show="!loading">
      <h1>{{ t("key2" }}</h1>
      <slot></slot>
    </div>
  </div>
</template>

<script>
import { ref } from "vue"
import store from "@/lib/store"; // your configured storage
import { useTranslation } from "@gelbehexe/debbie-vuex-i18n"

export default {
  name: "Layout",
  setup() {
    const loading = ref(true)
    
    const { t } = useTranslation(store)
    
    function handleTranslationLoaded() {
      loading.value = false;
    }

    return {
      t,
      loading,
      handleTranslationLoaded
    }
  }
}

</script>

Api


useLocalizationContextLoader(store: Store): {getContextualLocalization: function, loadDeferredLocalization: function}

Returns the following functions as object:

getContextualLocalization(contexts: string[]|string): {Promise}

Loads localization contexts directly

loadDeferredLocalization(): {Promise}

Loads previously added lazy contexts

If you are using the directive v-vuex-translation contextual loading is automatically triggered. Then there is no need for calling this function manually

useTranslation(store: Store): {trans: Function, transChoice: Function, t: Function, addDeferredLocalizationContext: Function}

Hint: Most of the functions are adopted from Laravel Localization, but not the __() because eslint does not like the underscores. Except: The locale parameter is not available.

Returns the following functions as object:

trans(key: string, replace?: {}): string

Simply translates a string.

See https://laravel.com/docs/8.x/helpers#method-trans

transChoice(key: string, number: Number, replace?: {}): string

Get a translation according to an integer value.

See https://laravel.com/docs/8.x/helpers#method-trans-choice

t(key: string, replace?: {}): string

Alias for trans

addDeferredLocalizationContext(context: string)

Adds a context for deferred loading.

Directives

For now there is only one directive:


v-vuex-translation

Other


Language data examples

You are not required to set all localization keys for fallback language since they are only used if not defined for default language

Initial Data
    {
        en: {
            en1: "English Only",
        },
        de: {
            key1: "Deutsch 1",
            key2: "Deutsch 2",
            en_de: "Englisch und Deutsch"
        }
    }
Contextual Data

Data coming from LanguageLoader. Existing keys will be overridden.

For sure this could happen intentionally or accidentally.

{
  en: {
    "context1.key3": "Contextual English 3",
  },
  de: {
    "context1.key1": "Context Deutsch 1",
    "context1.key2": "Context Deutsch 2",
    "context1.key4": "Context Deutsch 4",
  },
}

debbie-vuex-i18n's People

Contributors

gelbehexe avatar

Watchers

James Cloos avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.