|
1 |
| -import { reactive, Plugin, computed, ComputedRef, watchEffect } from 'vue' |
| 1 | +import { reactive, Plugin, computed, ComputedRef, watchEffect, ref, ComputedRef } from 'vue' |
2 | 2 | import { OptionsInterface } from './interfaces/options'
|
3 | 3 | import { PluginOptionsInterface } from './interfaces/plugin-options'
|
4 | 4 | import { LanguageInterface } from './interfaces/language'
|
@@ -26,6 +26,17 @@ const DEFAULT_OPTIONS: OptionsInterface = {
|
26 | 26 | onLoad: (lang: string) => {}
|
27 | 27 | }
|
28 | 28 |
|
| 29 | +/** |
| 30 | + * A computed property that reflects the current reactive language. |
| 31 | + * |
| 32 | + * This value is derived from the shared I18n instance. When the language |
| 33 | + * is updated via the I18n API, this computed value will automatically reflect |
| 34 | + * the new language. |
| 35 | + */ |
| 36 | +export const currentLocale: ComputedRef<string> = computed(() => { |
| 37 | + return I18n.getSharedInstance().getCurrentLanguage().value |
| 38 | +}) |
| 39 | + |
29 | 40 | /**
|
30 | 41 | * The default options, for the plugin.
|
31 | 42 | */
|
@@ -137,6 +148,9 @@ export class I18n {
|
137 | 148 | // Stores options for the current instance
|
138 | 149 | private options: OptionsInterface
|
139 | 150 |
|
| 151 | + // Stores a reactive reference to the current active language |
| 152 | + private currentLanguage = ref<string>(DEFAULT_OPTIONS.lang || DEFAULT_OPTIONS.fallbackLang) |
| 153 | + |
140 | 154 | // Stores messages for the currently active language
|
141 | 155 | private activeMessages: object = reactive({})
|
142 | 156 |
|
@@ -358,6 +372,7 @@ export class I18n {
|
358 | 372 | }
|
359 | 373 |
|
360 | 374 | this.options.lang = lang
|
| 375 | + this.currentLanguage.value = lang |
361 | 376 |
|
362 | 377 | for (const [key, value] of Object.entries(messages)) {
|
363 | 378 | this.activeMessages[key] = value
|
@@ -386,6 +401,13 @@ export class I18n {
|
386 | 401 | return this.options.lang || this.options.fallbackLang
|
387 | 402 | }
|
388 | 403 |
|
| 404 | + /** |
| 405 | + * Returns the reactive current active language |
| 406 | + */ |
| 407 | + getCurrentLanguage(): ComputedRef<string> { |
| 408 | + return computed(() => this.currentLanguage.value) |
| 409 | + } |
| 410 | + |
389 | 411 | /**
|
390 | 412 | * Checks if the language is loaded.
|
391 | 413 | */
|
|
0 commit comments