Skip to content

vue-i18n / general / Composer

Интерфейс: Composer<Messages, DateTimeFormats, NumberFormats, OptionLocale, ResourceLocales, Locales> ​

Интерфейсы Composer

Примечания ​

Это интерфейс для использования в Vue 3 Composition API.

Композиция Vue I18n ​

Расширяет ​

Параметры типа ​

Параметр типаТип по умолчанию
Messages extends Record<string, any>object
DateTimeFormats extends Record<string, any>object
NumberFormats extends Record<string, any>object
OptionLocaleLocale
ResourceLocales| PickupLocales<NonNullable<Messages>> | PickupLocales<NonNullable<DateTimeFormats>> | PickupLocales<NonNullable<NumberFormats>>
LocalesLocale extends GeneratedLocale ? GeneratedLocale : OptionLocale extends Locale ? IsNever<ResourceLocales> extends true ? Locale : ResourceLocales : OptionLocale | ResourceLocales

Методы ​

getDateTimeFormat() ​

ts
getDateTimeFormat<DateTimeSchema, LocaleSchema, Locale, Return>(locale): Return;

Получить формат даты и времени

Type Parameters ​

Type ParameterDefault typeDescription
DateTimeSchema extends Record<string, any>neverThe datetime format schema, default never
LocaleSchema extends stringstring-
Locale extends stringPickupLocales<NonNullable<DateTimeFormats>>-
ReturnIsNever<DateTimeSchema> extends true ? IsEmptyObject<DateTimeFormats> extends true ? RemoveIndexSignature<{ [key: string]: DateTimeFormatOptions; }> : NonNullable<DateTimeFormats>[Locale] : DateTimeSchema-

Parameters ​

ParameterTypeDescription
localeLocaleSchema | LocaleA target locale

Возвращает ​

Return

Формат даты и времени

Remarks ​

получить формат даты и времени из экземпляра Composer Composer#datetimeFormats.


getLocaleMessage() ​

ts
getLocaleMessage<MessageSchema, LocaleSchema, Locale, Return>(locale): Return;

Получить локализованное сообщение

Type Parameters ​

Type ParameterDefault typeDescription
MessageSchema extends LocaleMessage<VueMessageType>neverThe locale message schema, default never
LocaleSchema extends stringstring-
Locale extends stringPickupLocales<NonNullable<Messages>>-
ReturnIsNever<MessageSchema> extends true ? IsEmptyObject<Messages> extends true ? RemoveIndexSignature<{ [key: string]: LocaleMessageValue<VueMessageType>; }> : NonNullable<Messages>[Locale] : MessageSchema-

Parameters ​

ParameterTypeDescription
localeLocaleSchema | LocaleA target locale

Returns ​

Return

Locale messages

Remarks ​

получить локализованное сообщение из экземпляра Composer Composer#messages.


getMissingHandler() ​

ts
getMissingHandler(): MissingHandler | null;

Получить обработчик отсутствующих элементов

See about:

  • Composer#missing

Returns ​

MissingHandler | null

MissingHandler


getNumberFormat() ​

ts
getNumberFormat<NumberSchema, LocaleSchema, Locale, Return>(locale): Return;

Получить формат числа

Type Parameters ​

Type ParameterDefault typeDescription
NumberSchema extends Record<string, any>neverThe number format schema, default never
LocaleSchema extends stringstring-
Locale extends stringPickupLocales<NonNullable<NumberFormats>>-
ReturnIsNever<NumberSchema> extends true ? IsEmptyObject<NumberFormats> extends true ? RemoveIndexSignature<{ [key: string]: NumberFormatOptions; }> : NonNullable<NumberFormats>[Locale] : NumberSchema-

Parameters ​

ParameterTypeDescription
localeLocaleSchema | LocaleA target locale

Возвращает ​

Return

Формат числа

Remarks ​

get number format from Composer instance Composer#numberFormats.


getPostTranslationHandler() ​

ts
getPostTranslationHandler(): 
  | PostTranslationHandler<VueMessageType>
  | null;

Получить обработчик постперевода

See about:

  • Composer#missing

Returns ​

| PostTranslationHandler<VueMessageType> | null

PostTranslationHandler


mergeDateTimeFormat() ​

ts
mergeDateTimeFormat<DateTimeSchema, LocaleSchema, Locale, Formats>(locale, format): void;

Merge datetime format

Type Parameters ​

Type ParameterDefault typeDescription
DateTimeSchema extends Record<string, any>neverThe datetime format schema, default never
LocaleSchema extends stringstring-
Locale extends stringPickupLocales<NonNullable<DateTimeFormats>>-
FormatsIsNever<DateTimeSchema> extends true ? Record<string, any> : DateTimeSchema-

Parameters ​

ParameterTypeDescription
localeLocaleSchema | LocaleA target locale
formatFormatsA target datetime format

Returns ​

void

Remarks ​

Merge datetime format to Composer instance Composer#datetimeFormats.


mergeLocaleMessage() ​

ts
mergeLocaleMessage<MessageSchema, LocaleSchema, Locale, Message>(locale, message): void;

Merge locale message

Type Parameters ​

Type ParameterDefault typeDescription
MessageSchema extends LocaleMessage<VueMessageType>neverThe locale message schema, default never
LocaleSchema extends stringstring-
Locale extends stringPickupLocales<NonNullable<Messages>>-
MessageIsNever<MessageSchema> extends true ? Record<string, any> : MessageSchema-

Parameters ​

ParameterTypeDescription
localeLocaleSchema | LocaleA target locale
messageMessageA message

Returns ​

void

Remarks ​

Merge locale message to Composer instance Composer#messages.


mergeNumberFormat() ​

ts
mergeNumberFormat<NumberSchema, LocaleSchema, Locale, Formats>(locale, format): void;

Merge number format

Type Parameters ​

Type ParameterDefault typeDescription
NumberSchema extends Record<string, any>neverThe number format schema, default never
LocaleSchema extends stringstring-
Locale extends stringPickupLocales<NonNullable<NumberFormats>>-
FormatsIsNever<NumberSchema> extends true ? Record<string, any> : NumberSchema-

Parameters ​

ParameterTypeDescription
localeLocaleSchema | LocaleA target locale
formatFormatsA target number format

Returns ​

void

Remarks ​

Merge number format to Composer instance Composer#numberFormats.


setDateTimeFormat() ​

ts
setDateTimeFormat<DateTimeSchema, LocaleSchema, Locale, FormatsType, Formats>(locale, format): void;

Set datetime format

Type Parameters ​

Type ParameterDefault typeDescription
DateTimeSchema extends Record<string, any>neverThe datetime format schema, default never
LocaleSchema extends stringstring-
Locale extends stringPickupLocales<NonNullable<DateTimeFormats>>-
FormatsTypeIsNever<DateTimeSchema> extends true ? IsEmptyObject<DateTimeFormats> extends true ? RemoveIndexSignature<{ [key: string]: DateTimeFormatOptions; }> : NonNullable<DateTimeFormats>[Locale] : DateTimeSchema-
FormatsFormatsType-

Parameters ​

ParameterTypeDescription
localeLocaleSchema | LocaleA target locale
formatFormatsA target datetime format

Returns ​

void

Remarks ​

Set datetime format to Composer instance Composer#datetimeFormats.


setLocaleMessage() ​

ts
setLocaleMessage<MessageSchema, LocaleSchema, Locale, MessageType, Message>(locale, message): void;

Set locale message

Type Parameters ​

Type ParameterDefault typeDescription
MessageSchema extends LocaleMessage<VueMessageType>neverThe locale message schema, default never
LocaleSchema extends stringstring-
Locale extends stringPickupLocales<NonNullable<Messages>>-
MessageTypeIsNever<MessageSchema> extends true ? IsEmptyObject<Messages> extends true ? RemoveIndexSignature<{ [key: string]: LocaleMessageValue<VueMessageType>; }> : NonNullable<Messages>[Locale] : MessageSchema-
MessageMessageType-

Parameters ​

ParameterTypeDescription
localeLocaleSchema | LocaleA target locale
messageMessageA message

Returns ​

void

Remarks ​

Set locale message to Composer instance Composer#messages.


setMissingHandler() ​

ts
setMissingHandler(handler): void;

Set missing handler

See about:

  • Composer#missing

Parameters ​

ParameterTypeDescription
handlerMissingHandler | nullA MissingHandler

Returns ​

void


setNumberFormat() ​

ts
setNumberFormat<NumberSchema, LocaleSchema, Locale, FormatsType, Formats>(locale, format): void;

Set number format

Type Parameters ​

Type ParameterDefault typeDescription
NumberSchema extends Record<string, any>neverThe number format schema, default never
LocaleSchema extends stringstring-
Locale extends stringPickupLocales<NonNullable<NumberFormats>>-
FormatsTypeIsNever<NumberSchema> extends true ? IsEmptyObject<NumberFormats> extends true ? RemoveIndexSignature<{ [key: string]: NumberFormatOptions; }> : NonNullable<NumberFormats>[Locale] : NumberSchema-
FormatsFormatsType-

Parameters ​

ParameterTypeDescription
localeLocaleSchema | LocaleA target locale
formatFormatsA target number format

Returns ​

void

Remarks ​

Set number format to Composer instance Composer#numberFormats.


setPostTranslationHandler() ​

ts
setPostTranslationHandler(handler): void;

Set post translation handler

See about:

  • Composer#missing

Parameters ​

ParameterTypeDescription
handler| PostTranslationHandler<VueMessageType> | nullA PostTranslationHandler

Returns ​

void


te() ​

ts
te<Str, Key>(key, locale?): boolean;

Translation locale message exist

Type Parameters ​

Type ParameterDefault type
Str extends string-
Key extends string | number | symbolPickupKeys<Messages>

Parameters ​

ParameterTypeDescription
keyStr | KeyA target locale message key
locale?LocalesA locale, it will be used over than global scope or local scope

Returns ​

boolean

If found locale message, true, else false, Note that false is returned even if the value present in the key is not translatable, yet if translateExistCompatible is set to true, it will return true if the key is available, even if the value is not translatable.

Remarks ​

whether do exist locale message on Composer instance Composer#messages.

If you specified locale, check the locale messages of locale.


tm() ​

ts
tm<Key, ResourceKeys, Locale, Target, Return>(key): Return;

Locale messages getter

Type Parameters ​

Type ParameterDefault type
Key extends string-
ResourceKeys extends string | number | symbolPickupKeys<Messages>
Locale extends stringPickupLocales<NonNullable<Messages>>
TargetIsEmptyObject<Messages> extends false ? NonNullable<Messages>[Locale] : RemoveIndexSignature<{ [key: string]: LocaleMessageValue<VueMessageType>; }>
ReturnResourceKeys extends ResourcePath<Target> ? ResourceValue<Target, ResourceKeys<ResourceKeys>> : Record<string, any>

Parameters ​

ParameterTypeDescription
keyKey | ResourceKeysA target locale message key

Returns ​

Return

Locale messages

Remarks ​

If I18nScope 'local' or Some UseI18nOptions are specified at useI18n, it’s translated in preferentially local scope locale messages than global scope locale messages.

Based on the current locale, locale messages will be returned from Composer instance messages.

If you change the locale, the locale messages returned will also correspond to the locale.

If there are no locale messages for the given key in the composer instance messages, they will be returned with fallbacking.

WARNING

You need to use rt for the locale message returned by tm. see the rt details.

Example ​

template block:

html
<div class="container">
  <template v-for="content in tm('contents')">
    <h2>{{ rt(content.title) }}</h2>
    <p v-for="paragraph in content.paragraphs">
     {{ rt(paragraph) }}
    </p>
  </template>
</div>

script block:

js
import { defineComponent } from 'vue
import { useI18n } from 'vue-i18n'

export default defineComponent({
  setup() {
    const { rt, tm } = useI18n({
      messages: {
        en: {
          contents: [
            {
              title: 'Title1',
              // ...
              paragraphs: [
                // ...
              ]
            }
          ]
        }
      }
      // ...
    })
    // ...
    return { ... , rt, tm }
  }
})

Свойства ​

availableLocales ​

ts
readonly availableLocales: ComputedRef<Locales[]>;

Remarks ​

Список доступных локалей в messages в лексикографическом порядке.


d ​

ts
d: ComposerDateTimeFormatting<DateTimeFormats, Locales, RemoveIndexSignature<{
[key: string]: DateTimeFormatOptions;
}>>;

Форматирование даты и времени

Remarks ​

За подробными функциями обращайтесь к ComposerDateTimeFormatting


datetimeFormats ​

ts
readonly datetimeFormats: ComputedRef<{ [K in string | number | symbol]: DateTimeFormats[K] }>;

Remarks ​

Форматы даты и времени локализации.

See about:


escapeParameter ​

ts
escapeParameter: boolean;

Remarks ​

Указывает, будут ли параметры интерполяции экранированы перед переводом сообщения.

See about:


fallbackFormat ​

ts
fallbackFormat: boolean;

Remarks ​

Указывает, следует ли подавлять предупреждения при возврате к fallbackLocale или корневому уровню.

See about:


fallbackLocale ​

ts
fallbackLocale: WritableComputedRef<FallbackLocales<Locales>>;

Remarks ​

Текущие резервные локали, используемые этим экземпляром Composer.

See about:


fallbackRoot ​

ts
fallbackRoot: boolean;

Remarks ​

Следует ли возвращаться к глобальной области (корневому уровню) локализации при неудачной локализации.

See about:


fallbackWarn ​

ts
fallbackWarn: boolean | RegExp;

Remarks ​

Следует ли подавлять предупреждения о возврате при неудачной локализации.

See about:


id ​

ts
id: number;

Remarks ​

ID экземпляра.


inheritLocale ​

ts
inheritLocale: boolean;

Remarks ​

Следует ли наследовать уровень локали корня к локали локализации компонента.

See about:


isGlobal ​

ts
readonly isGlobal: boolean;

Remarks ​

Является ли этот экземпляр composer глобальным или нет


locale ​

ts
locale: WritableComputedRef<Locales>;

Remarks ​

Текущая локаль, используемая этим экземпляром Composer.

If the locale contains a territory and a dialect, this locale contains an implicit fallback.

See about:


messages ​

ts
readonly messages: ComputedRef<{ [K in string | number | symbol]: Messages[K] }>;

Remarks ​

Локализованные сообщения.

See about:


missingWarn ​

ts
missingWarn: boolean | RegExp;

Remarks ​

Следует ли подавлять предупреждения, выводимые при неудачной локализации.

See about:


modifiers ​

ts
readonly modifiers: LinkedModifiers<VueMessageType>;

Remarks ​

Пользовательские модификаторы для связанных сообщений.

See about:


n ​

ts
n: ComposerNumberFormatting<NumberFormats, Locales, RemoveIndexSignature<{
[key: string]: NumberFormatOptions;
}>>;

Number Formatting

Remarks ​

За подробными функциями обращайтесь к ComposerNumberFormatting


numberFormats ​

ts
readonly numberFormats: ComputedRef<{ [K in string | number | symbol]: NumberFormats[K] }>;

Remarks ​

Форматы чисел локализации.

See about:


pluralRules ​

ts
readonly pluralRules: PluralizationRules;

Remarks ​

Набор правил для словесного множественного числа

See about:


rt ​

ts
rt: ComposerResolveLocaleMessageTranslation<Locales>;

Разрешить перевод локализованного сообщения

Remarks ​

About details functions, See the ComposerResolveLocaleMessageTranslation


t ​

ts
t: ComposerTranslation<Messages, Locales, RemoveIndexSignature<{
[key: string]: LocaleMessageValue<VueMessageType>;
}>>;

Перевод локализованного сообщения

Remarks ​

About details functions, See the ComposerTranslation


warnHtmlMessage ​

ts
warnHtmlMessage: boolean;

Remarks ​

Следует ли разрешать использование локализованных сообщений с форматированием HTML.

Если вы установите false, будет проверяться локализованные сообщения на экземпляре Composer.

Если вы установите true, предупреждение будет выведено в консоль.

See about: