diff --git a/404.html b/404.html new file mode 100644 index 000000000..b8f9e043e --- /dev/null +++ b/404.html @@ -0,0 +1,21 @@ + + + + + + Vue I18n + + + + + + + + + +

404

How did we get here?
+ Take me home. +
+ + + diff --git a/api/index.html b/api/index.html new file mode 100644 index 000000000..d58e70b7d --- /dev/null +++ b/api/index.html @@ -0,0 +1,190 @@ + + + + + + API references | Vue I18n + + + + + + + + + +

# API references

# Extension of Vue

# Vue constructor options

# i18n

  • Type: I18nOptions

Component based localization option.

  • See also: VueI18n class constructor options

# Vue injected methods

# $t

  • Arguments:

    • {Path} key: required
    • {Locale} locale: optional
    • {Array | Object} values: optional
  • Return: TranslateResult

Localize the locale message of key. Localize in preferentially component locale messages than global locale messages. If not specified component locale messages, localize with global locale messages. If you specified locale, localize the locale messages of locale. If you specified key of list / named formatting local messages, you must specify values too. For values more details see Formatting.

If default pluralization does not suit your needs, see pluralization rules in constructor options and custom pluralization.

Tip

Note that you need to guarantee this context equal to component instance in lifecycle methods (e.g. in data options, const $t = this.$t.bind(this)).

# $tc

  • Arguments:

    • {Path} key: required
    • {number} choice: optional, default 1
    • {Locale} locale: optional
    • {string | Array | Object} values: optional
  • Return: TranslateResult

Localize the locale message of key with pluralization. Localize in preferentially component locale messages than global locale messages. If not specified component locale messages, localize with global locale messages. If you specified locale, localize the locale messages of locale. If you will specify string value to values, localize the locale messages of value. If you will specify Array or Object value to values, you must specify with values of $t.

Tip

Note that you need to guarantee this context equal to component instance in lifecycle methods (e.g. in data options, const $tc = this.$tc.bind(this)).

# $te

  • Arguments:

    • {Path} key: required
    • {Locale} locale: optional
  • Return: boolean

Check whether key exists. In Vue instance, If not specified component locale messages, check with global locale messages. If you specified locale, check the locale messages of locale.

Tip

Note that you need to guarantee this context equal to component instance in lifecycle methods (e.g. in data options, const $te = this.$te.bind(this)).

# $d

🆕 7.0+

  • Arguments:

    • {number | Date} value: required
    • {Path | Object} key: optional
    • {Locale | Object} locale: optional
  • Return: DateTimeFormatResult

Localize the datetime of value with datetime format of key. The datetime format of key need to register to dateTimeFormats option of VueI18n class, and depend on locale option of VueI18n constructor. If you will specify locale argument, it will have priority over locale option of VueI18n constructor.

If the datetime format of key not exist in dateTimeFormats option, fallback to depend on fallbackLocale option of VueI18n constructor.

Tip

Note that you need to guarantee this context equal to component instance in lifecycle methods (e.g. in data options, const $d = this.$d.bind(this)).

# $n

🆕 7.0+

  • Arguments:

    • {number} value: required
    • {Path | Object} format: optional
    • {Locale} locale: optional
  • Return: NumberFormatResult

Localize the number of value with number format of format. The number format of format need to register to numberFormats option of VueI18n class, and depend on locale option of VueI18n constructor. If you will specify locale argument, it will have priority over locale option of VueI18n constructor.

If the number format of format not exist in numberFormats option, fallback to depend on fallbackLocale option of VueI18n constructor.

If the second format argument specified as an object, it should have the following properties:

  • key {Path}: optional, number format
  • locale {Locale}: optional, locale
  • compactDisplay {string}: optional, number format option
  • currency {string}: optional, number format option
  • currencyDisplay {string}: optional, number format option
  • currencySign {string}: optional, number format option
  • localeMatcher {string}: optional, number format option
  • notation {string}: optional, number format option
  • numberingSystem {string}: optional, number format option
  • signDisplay {string}: optional, number format option
  • style {string}: optional, number format option
  • unit {string}: optional, number format option
  • unitDisplay {string}: optional, number format option
  • useGrouping {boolean}: optional, number format option
  • minimumIntegerDigits {string}: optional, number format option
  • minimumFractionDigits {string}: optional, number format option
  • maximumFractionDigits {string}: optional, number format option
  • minimumSignificantDigits {string}: optional, number format option
  • maximumSignificantDigits {string}: optional, number format option

Any specified number format options will have priority over numberFormats of VueI18n constructor.

Tip

Note that you need to guarantee this context equal to component instance in lifecycle methods (e.g. in data options, const $n = this.$n.bind(this)).

# Injected properties

# $i18n

  • Type: I18n

  • Read only

Get a VueI18n instance. If you are specify.

If you have specified an i18n option at component options, you will be able to get a VueI18n instance at the component, Otherwise, you will be able get root VueI18n instance.

# VueI18n class

VueI18n class implement I18n interface of flowtype definitions (opens new window)

# Static properties

# version

  • Type: string

vue-i18n version.

# availabilities

🆕 7.0+

  • Type: IntlAvailability

Whether the following internationalization features are available:

  • {boolean} dateTimeFormat: locale sensitive datetime formatting

  • {boolean} numberFormat: locale sensitive number formatting

The above internationalization features are depends on the browser environments (opens new window), due to implement with ECMAScript Internationalization API (ECMA-402).

# Constructor options

You can specify the below some options of I18nOptions constructor options of flowtype definitions (opens new window)

# locale

  • Type: Locale

  • Default: 'en-US'

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

# fallbackLocale

  • Type: FallbackLocale

  • Default: false

The locale of fallback localization. For more complex fallback definitions see fallback.

# messages

  • Type: LocaleMessages

  • Default: {}

The locale messages of localization.

# dateTimeFormats

🆕 7.0+

  • Type: DateTimeFormats

  • Default: {}

The datetime formats of localization.

# numberFormats

🆕 7.0+

  • Type: NumberFormats

  • Default: {}

The number formats of localization.

# formatter

  • Type: Formatter

  • Default: Built in formatter

The formatter that implemented with Formatter interface.

# modifiers

🆕 8.15.0+

  • Type: Modifiers

  • Default: lower and upper modifiers

Modifiers functions for linked messages

# missing

  • Type: MissingHandler

  • Default: null

A handler for localization missing. The handler gets called with the localization target locale, localization path key, the Vue instance and values.

If missing handler is assigned, and occurred localization missing, it's not warned.

# fallbackRoot

  • Type: Boolean

  • Default: true

In the component localization, whether to fall back to root level (global) localization when localization fails.

If false, it's warned, and is returned the key.

# fallbackRootWithEmptyString

🆕 8.26+

  • Type: Boolean

  • Default: true

    In the component localization, whether to fall back to root level (global) localization when local message is an empty string.

    Please note the default behavior in vue-i18n 9.x is to not falling back to root for local message that is empty string.

    If false, the empty local message will not fall back to root and will be kept as empty string.

# sync

  • Type: Boolean

  • Default: true

Whether synchronize the root level locale to the component localization locale.

If false, regardless of the root level locale, localize for each component locale.

# silentTranslationWarn

6.1+, 🆙 8.13

  • Type: Boolean | RegExp

  • Default: false

Whether suppress warnings outputted when localization fails.

If true, suppress localization fail warnings. +If you use regular expression, you can suppress localization fail warnings that it match with translation key (e.g. $t).

# silentFallbackWarn

🆕 8.8+, 🆙 8.13

  • Type: Boolean | RegExp
  • Default: false

Whether suppress warnings when falling back to either fallbackLocale or root.

If true, warnings will be generated only when no translation is available at all, and not for fallbacks. +If you use regular expression, you can suppress the fallback warnings that it match key (e.g. $t).

# pluralizationRules

8.5+

  • Type: PluralizationRules

  • Default: {}

A set of rules for word pluralization in a following format:

  {
+    // Key - locale for the rule to be applied to.
+    // Value - mapping function that maps a choice index from `$tc` to the actual choice of the plural word. (See getChoiceIndex for details)
+    'pt': function(choice, choiceIndex) => Number/* index of the plural word */;
+    'ru': function(choice, choiceIndex) => Number/* index of the plural word */;
+    'en': function(choice, choiceIndex) => Number/* index of the plural word */;
+    'jp': function(choice, choiceIndex) => Number/* index of the plural word */;
+  }
+

# preserveDirectiveContent

8.7+

  • Type: Boolean

  • Default: false

Whether v-t directive's element should preserve textContent after directive is unbinded.

# warnHtmlInMessage

8.11+

  • Type: WarnHtmlInMessageLevel

  • Default: off

Whether to allow the use locale messages of HTML formatting. See the warnHtmlInMessage property.

Important!!

In next major version, warnHtmlInMessage option is warn as default.

# sharedMessages

8.12+

  • Type: LocaleMessages

  • Default: undefined

The shared locale messages of localization for components. More detail see Component based localization.

# postTranslation

8.16+

  • Type: PostTranslationHandler

  • Default: null

A handler for post processing of translation. The handler gets after being called with the $t, t, $tc, and tc.

This handler is useful if you want to filter on translated text such as space trimming.

# componentInstanceCreatedListener

8.18+

  • Type: ComponentInstanceCreatedListener

  • Default: null

A handler for getting notified when component-local instance was created. The handler gets called with new and old (root) VueI18n instances.

This handler is useful when extending the root VueI18n instance and wanting to also apply those extensions to component-local instance.

# escapeParameterHtml

8.22+

  • Type: Boolean

  • Default: false

If escapeParameterHtml is configured as true then interpolation parameters are escaped before the message is translated. +This is useful when translation output is used in v-html and the translation resource contains html markup (e.g. <b> +around a user provided value). This usage pattern mostly occurs when passing precomputed text strings into UI compontents.

The escape process involves replacing the following symbols with their respective HTML character entities: <, >, ", '.

Setting escapeParameterHtml as true should not break existing functionality but provides a safeguard against a subtle +type of XSS attack vectors.

# Properties

# locale

  • Type: Locale

  • Read/Write

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

# fallbackLocale

  • Type: FallbackLocale

  • Read/Write

The locale of fallback localization. For more complex fallback definitions see fallback.

# messages

  • Type: LocaleMessages

  • Read only

The locale messages of localization.

# dateTimeFormats

🆕 7.0+

  • Type: DateTimeFormats

  • Read only

The datetime formats of localization.

# numberFormats

🆕 7.0+

  • Type: NumberFormats

  • Read only

The number formats of localization.

# availableLocales

🆕 8.9.0+

  • Type: Locale[]

  • Read only

The list of available locales in messages in lexical order.

# missing

  • Type: MissingHandler

  • Read/Write

A handler for localization missing.

# formatter

  • Type: Formatter

  • Read/Write

The formatter that implemented with Formatter interface.

# silentTranslationWarn

6.1+, 🆙 8.13

  • Type: Boolean | RegExp

  • Read/Write

Whether suppress warnings outputted when localization fails.

# silentFallbackWarn

🆕 8.8+, 🆙 8.13

  • Type: Boolean | RegExp

  • Read/Write

Whether suppress fallback warnings when localization fails.

# pluralizationRules

8.5+

  • Type: PluralizationRules

  • Read/Write

A set of locale-dependent rules for word pluralization.

# preserveDirectiveContent

8.7+

  • Type: Boolean

  • Read/Write

Whether v-t directive's element should preserve textContent after directive is unbinded.

# warnHtmlInMessage

8.11+

  • Type: WarnHtmlInMessageLevel

  • Read/Write

Whether to allow the use locale messages of HTML formatting.

If you set warn orerror, will check the locale messages on the VueI18n instance.

If you are specified warn, a warning will be output at console.

If you are specified error will occurred an Error.

In VueI18n instance, set the off as default.

# postTranslation

8.16+

  • Type: PostTranslationHandler

  • Read/Write

A handler for post processing of translation.

# Methods

# getChoiceIndex

  • Arguments:

    • {number} choice
    • {number} choicesLength
  • Return: finalChoice {number}

Get pluralization index for current pluralizing number and a given amount of choices. +Can be overridden through prototype mutation:

VueI18n.prototype.getChoiceIndex = /* custom implementation */
+

However, for most usages pluralizationRules constructor option should be enough.

# getLocaleMessage( locale )

  • Arguments:

    • {Locale} locale
  • Return: LocaleMessageObject

Get the locale message of locale.

# setLocaleMessage( locale, message )

  • Arguments:

    • {Locale} locale
    • {LocaleMessageObject} message

Set the locale message of locale.

NOTE

8.11+

If you set warn orerror in the warnHtmlInMessage property, when this method is executed, it will check if HTML formatting is used for locale message.

# mergeLocaleMessage( locale, message )

6.1+

  • Arguments:

    • {Locale} locale
    • {LocaleMessageObject} message

Merge the registered locale messages with the locale message of locale.

NOTE

8.11+

If you set warn orerror in the warnHtmlInMessage property, when this method is executed, it will check if HTML formatting is used for locale message.

# t( key, [locale], [values] )

  • Arguments:

    • {Path} key: required
    • {Locale} locale: optional
    • {Array | Object} values: optional
  • Return: : TranslateResult

This is the same as the Function returned with $t method. More detail see $t.

# tc( key, [choice], [values] )

  • Arguments:

    • {Path} key: required
    • {number} choice: optional, default 1
    • {string | Array | Object} values: optional
  • Return: TranslateResult

This is the same as the Function returned $tc method. More detail see $tc.

# te( key, [locale] )

  • Arguments:

    • {string} key: required
    • {Locale} locale: optional
  • Return: boolean

Check whether key path exists in global locale message. If you specified locale, check the locale message of locale.

# getDateTimeFormat ( locale )

🆕 7.0+

  • Arguments:

    • {Locale} locale
  • Return: DateTimeFormat

Get the datetime format of locale.

# setDateTimeFormat ( locale, format )

🆕 7.0+

  • Arguments:

    • {Locale} locale
    • {DateTimeFormat} format

Set the datetime format of locale.

# mergeDateTimeFormat ( locale, format )

🆕 7.0+

  • Arguments:

    • {Locale} locale
    • {DateTimeFormat} format

Merge the registered datetime formats with the datetime format of locale.

# d( value, [key], [locale] )

🆕 7.0+

  • Arguments:

    • {number | Date} value: required
    • {Path | Object} key: optional
    • {Locale | Object} locale: optional
  • Return: DateTimeFormatResult

This is the same as $d method of Vue instance method. More detail see $d.

# getNumberFormat ( locale )

🆕 7.0+

  • Arguments:

    • {Locale} locale
  • Return: NumberFormat

Get the number format of locale.

# setNumberFormat ( locale, format )

🆕 7.0+

  • Arguments:

    • {Locale} locale
    • {NumberFormat} format

Set the number format of locale.

# mergeNumberFormat ( locale, format )

🆕 7.0+

  • Arguments:

    • {Locale} locale
    • {NumberFormat} format

Merge the registered number formats with the number format of locale.

# n( value, [format], [locale] )

🆕 7.0+

  • Arguments:

    • {number} value: required
    • {Path | Object} format: optional
    • {Locale} locale: optional
  • Return: NumberFormatResult

This is the same as $n method of Vue instance method. More detail see $n.

# Directives

🆕 7.3+

# v-t

  • Expects: string | Object

  • Modifiers:

    • .preserve: (8.7.0+) preserves element textContent when directive is unbinded.
  • Details:

Update the element textContent that localized with locale messages. You can use string syntax or object syntax. string syntax can be specified as a keypath of locale messages. If you can be used object syntax, you need to specify as the object key the following params:

  • path: required, key of locale messages
  • locale: optional, locale
  • args: optional, for list or named formatting

NOTE

The element textContent will be cleared by default when v-t directive is unbinded. This might be undesirable situation when used inside transitions (opens new window). To preserve textContent data after directive unbind use .preserve modifier or global preserveDirectiveContent option.

  • Examples:
<!-- string syntax: literal -->
+<p v-t="'foo.bar'"></p>
+
+<!-- string syntax: binding via data or computed props -->
+<p v-t="msg"></p>
+
+<!-- object syntax: literal -->
+<p v-t="{ path: 'hi', locale: 'ja', args: { name: 'kazupon' } }"></p>
+
+<!-- object syntax: binding via data or computed props -->
+<p v-t="{ path: greeting, args: { name: fullName } }"></p>
+
+<!-- with preserve modifier -->
+<p v-t.preserve="'foo.bar'"></p>
+

# Components

# i18n functional component

🆕 7.0+

# Props:

  • path {Path}: required, keypath of locale messages
  • locale {Locale}: optional, locale
  • tag {string | boolean | Object}: optional, default 'span'
  • places {Array | Object}: optional (7.2+)

Important!!

In next major version, places prop is deprecated. Please switch to slots syntax.

# Usage:

<div id="app">
+  <!-- ... -->
+  <i18n path="term" tag="label" for="tos">
+    <a :href="url" target="_blank">{{ $t('tos') }}</a>
+  </i18n>
+  <!-- ... -->
+</div>
+
const messages = {
+  en: {
+    tos: 'Term of Service',
+    term: 'I accept xxx {0}.'
+  },
+  ja: {
+    tos: '利用規約',
+    term: '私は xxx の{0}に同意します。'
+  }
+}
+
+const i18n = new VueI18n({
+  locale: 'en',
+  messages
+})
+new Vue({
+  i18n,
+  data: {
+    url: '/term'
+  }
+}).$mount('#app')
+

# See also:

Component interpolation

# i18n-n functional component

🆕 8.10+

# Props:

  • value {number}: required, number to format
  • format {string | NumberFormatOptions}: optional, number format name or object with explicit format options
  • locale {Locale}: optional, locale
  • tag {string | boolean | Object}: optional, default 'span'

# Usage:

<div id="app">
+  <!-- ... -->
+  <i18n-n :value="money" format="currency" tag="label">
+    <span v-slot:currency="slotProps" class="font-weight: bold">{{ slotProps.currency }}<span>
+  </i18n-n>
+  <!-- ... -->
+</div>
+
var numberFormats = {
+  'en-US': {
+    currency: {
+      style: 'currency', currency: 'USD'
+    }
+  },
+  'ja-JP': {
+    currency: {
+      style: 'currency', currency: 'JPY'
+    }
+  }
+}
+
+const i18n = new VueI18n({
+  locale: 'en-US',
+  numberFormats
+})
+new Vue({
+  i18n,
+  data: {
+    money: 10234,
+  }
+}).$mount('#app')
+

# Scoped slots

<i18n-n> functional component can accept a number of named scoped slots. List of supported slot names is based on Intl.NumberFormat.formatToParts() output types (opens new window):

  • currency
  • decimal
  • fraction
  • group
  • infinity
  • integer
  • literal
  • minusSign
  • nan
  • plusSign
  • percentSign

Each of these named scoped slots will accept three scope parameters:

  • [slotName] {FormattedNumberPartType}: parameter of the same name as actual slot name (like integer)
  • index {Number}: index of the specific part in the array of number parts
  • parts {Array}: array of all formatted number parts

# See also:

Number custom formatting

# Special Attributes

# place

🆕 7.2+

# Expects: {number | string}

Used on component interpolation to indicate which index of list formatting or key of named formatting.

For detailed usage, see the guide section linked below.

# See also:

Component interpolation

+ + + diff --git a/assets/css/0.styles.dc7beab8.css b/assets/css/0.styles.dc7beab8.css new file mode 100644 index 000000000..a1af4cb74 --- /dev/null +++ b/assets/css/0.styles.dc7beab8.css @@ -0,0 +1 @@ +code[class*=language-],pre[class*=language-]{color:#ccc;background:none;font-family:Consolas,Monaco,Andale Mono,Ubuntu Mono,monospace;font-size:1em;text-align:left;white-space:pre;word-spacing:normal;word-break:normal;word-wrap:normal;line-height:1.5;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-hyphens:none;-ms-hyphens:none;hyphens:none}pre[class*=language-]{padding:1em;margin:.5em 0;overflow:auto}:not(pre)>code[class*=language-],pre[class*=language-]{background:#2d2d2d}:not(pre)>code[class*=language-]{padding:.1em;border-radius:.3em;white-space:normal}.token.block-comment,.token.cdata,.token.comment,.token.doctype,.token.prolog{color:#999}.token.punctuation{color:#ccc}.token.attr-name,.token.deleted,.token.namespace,.token.tag{color:#e2777a}.token.function-name{color:#6196cc}.token.boolean,.token.function,.token.number{color:#f08d49}.token.class-name,.token.constant,.token.property,.token.symbol{color:#f8c555}.token.atrule,.token.builtin,.token.important,.token.keyword,.token.selector{color:#cc99cd}.token.attr-value,.token.char,.token.regex,.token.string,.token.variable{color:#7ec699}.token.entity,.token.operator,.token.url{color:#67cdcc}.token.bold,.token.important{font-weight:700}.token.italic{font-style:italic}.token.entity{cursor:help}.token.inserted{color:green}.theme-default-content code{color:#476582;padding:.25rem .5rem;margin:0;font-size:.85em;background-color:rgba(27,31,35,.05);border-radius:3px}.theme-default-content code .token.deleted{color:#ec5975}.theme-default-content code .token.inserted{color:#3eaf7c}.theme-default-content pre,.theme-default-content pre[class*=language-]{line-height:1.4;padding:1.25rem 1.5rem;margin:.85rem 0;background-color:#282c34;border-radius:6px;overflow:auto}.theme-default-content pre[class*=language-] code,.theme-default-content pre code{color:#fff;padding:0;background-color:transparent;border-radius:0}div[class*=language-]{position:relative;background-color:#282c34;border-radius:6px}div[class*=language-] .highlight-lines{-webkit-user-select:none;user-select:none;padding-top:1.3rem;position:absolute;top:0;left:0;width:100%;line-height:1.4}div[class*=language-] .highlight-lines .highlighted{background-color:rgba(0,0,0,.66)}div[class*=language-] pre,div[class*=language-] pre[class*=language-]{background:transparent;position:relative;z-index:1}div[class*=language-]:before{position:absolute;z-index:3;top:.8em;right:1em;font-size:.75rem;color:hsla(0,0%,100%,.4)}div[class*=language-]:not(.line-numbers-mode) .line-numbers-wrapper{display:none}div[class*=language-].line-numbers-mode .highlight-lines .highlighted{position:relative}div[class*=language-].line-numbers-mode .highlight-lines .highlighted:before{content:" ";position:absolute;z-index:3;left:0;top:0;display:block;width:3.5rem;height:100%;background-color:rgba(0,0,0,.66)}div[class*=language-].line-numbers-mode pre{padding-left:4.5rem;vertical-align:middle}div[class*=language-].line-numbers-mode .line-numbers-wrapper{position:absolute;top:0;width:3.5rem;text-align:center;color:hsla(0,0%,100%,.3);padding:1.25rem 0;line-height:1.4}div[class*=language-].line-numbers-mode .line-numbers-wrapper br{-webkit-user-select:none;user-select:none}div[class*=language-].line-numbers-mode .line-numbers-wrapper .line-number{position:relative;z-index:4;-webkit-user-select:none;user-select:none;font-size:.85em}div[class*=language-].line-numbers-mode:after{content:"";position:absolute;z-index:2;top:0;left:0;width:3.5rem;height:100%;border-radius:6px 0 0 6px;border-right:1px solid rgba(0,0,0,.66);background-color:#282c34}div[class~=language-js]:before{content:"js"}div[class~=language-ts]:before{content:"ts"}div[class~=language-html]:before{content:"html"}div[class~=language-md]:before{content:"md"}div[class~=language-vue]:before{content:"vue"}div[class~=language-css]:before{content:"css"}div[class~=language-sass]:before{content:"sass"}div[class~=language-scss]:before{content:"scss"}div[class~=language-less]:before{content:"less"}div[class~=language-stylus]:before{content:"stylus"}div[class~=language-go]:before{content:"go"}div[class~=language-java]:before{content:"java"}div[class~=language-c]:before{content:"c"}div[class~=language-sh]:before{content:"sh"}div[class~=language-yaml]:before{content:"yaml"}div[class~=language-py]:before{content:"py"}div[class~=language-docker]:before{content:"docker"}div[class~=language-dockerfile]:before{content:"dockerfile"}div[class~=language-makefile]:before{content:"makefile"}div[class~=language-javascript]:before{content:"js"}div[class~=language-typescript]:before{content:"ts"}div[class~=language-markup]:before{content:"html"}div[class~=language-markdown]:before{content:"md"}div[class~=language-json]:before{content:"json"}div[class~=language-ruby]:before{content:"rb"}div[class~=language-python]:before{content:"py"}div[class~=language-bash]:before{content:"sh"}div[class~=language-php]:before{content:"php"}.custom-block .custom-block-title{font-weight:600;margin-bottom:-.4rem}.custom-block.danger,.custom-block.tip,.custom-block.warning{padding:.1rem 1.5rem;border-left-width:.5rem;border-left-style:solid;margin:1rem 0}.custom-block.tip{background-color:#f3f5f7;border-color:#42b983}.custom-block.warning{background-color:rgba(255,229,100,.3);border-color:#e7c000;color:#6b5900}.custom-block.warning .custom-block-title{color:#b29400}.custom-block.warning a{color:#2c3e50}.custom-block.danger{background-color:#ffe6e6;border-color:#c00;color:#4d0000}.custom-block.danger .custom-block-title{color:#900}.custom-block.danger a{color:#2c3e50}.custom-block.details{display:block;position:relative;border-radius:2px;margin:1.6em 0;padding:1.6em;background-color:#eee}.custom-block.details h4{margin-top:0}.custom-block.details figure:last-child,.custom-block.details p:last-child{margin-bottom:0;padding-bottom:0}.custom-block.details summary{outline:none;cursor:pointer}.arrow{display:inline-block;width:0;height:0}.arrow.up{border-bottom:6px solid #ccc}.arrow.down,.arrow.up{border-left:4px solid transparent;border-right:4px solid transparent}.arrow.down{border-top:6px solid #ccc}.arrow.right{border-left:6px solid #ccc}.arrow.left,.arrow.right{border-top:4px solid transparent;border-bottom:4px solid transparent}.arrow.left{border-right:6px solid #ccc}.theme-default-content:not(.custom){max-width:740px;margin:0 auto;padding:2rem 2.5rem}@media (max-width:959px){.theme-default-content:not(.custom){padding:2rem}}@media (max-width:419px){.theme-default-content:not(.custom){padding:1.5rem}}.table-of-contents .badge{vertical-align:middle}body,html{padding:0;margin:0;background-color:#fff}body{font-family:-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Oxygen,Ubuntu,Cantarell,Fira Sans,Droid Sans,Helvetica Neue,sans-serif;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;font-size:16px;color:#2c3e50}.page{padding-left:20rem}.navbar{z-index:20;right:0;height:3.6rem;background-color:#fff;box-sizing:border-box;border-bottom:1px solid #eaecef}.navbar,.sidebar-mask{position:fixed;top:0;left:0}.sidebar-mask{z-index:9;width:100vw;height:100vh;display:none}.sidebar{font-size:16px;background-color:#fff;width:20rem;position:fixed;z-index:10;margin:0;top:3.6rem;left:0;bottom:0;box-sizing:border-box;border-right:1px solid #eaecef;overflow-y:auto}.theme-default-content:not(.custom)>:first-child{margin-top:3.6rem}.theme-default-content:not(.custom) a:hover{text-decoration:underline}.theme-default-content:not(.custom) p.demo{padding:1rem 1.5rem;border:1px solid #ddd;border-radius:4px}.theme-default-content:not(.custom) img{max-width:100%}.theme-default-content.custom{padding:0;margin:0}.theme-default-content.custom img{max-width:100%}a{font-weight:500;text-decoration:none}a,p a code{color:#3eaf7c}p a code{font-weight:400}kbd{background:#eee;border:.15rem solid #ddd;border-bottom:.25rem solid #ddd;border-radius:.15rem;padding:0 .15em}blockquote{font-size:1rem;color:#999;border-left:.2rem solid #dfe2e5;margin:1rem 0;padding:.25rem 0 .25rem 1rem}blockquote>p{margin:0}ol,ul{padding-left:1.2em}strong{font-weight:600}h1,h2,h3,h4,h5,h6{font-weight:600;line-height:1.25}.theme-default-content:not(.custom)>h1,.theme-default-content:not(.custom)>h2,.theme-default-content:not(.custom)>h3,.theme-default-content:not(.custom)>h4,.theme-default-content:not(.custom)>h5,.theme-default-content:not(.custom)>h6{margin-top:-3.1rem;padding-top:4.6rem;margin-bottom:0}.theme-default-content:not(.custom)>h1:first-child,.theme-default-content:not(.custom)>h2:first-child,.theme-default-content:not(.custom)>h3:first-child,.theme-default-content:not(.custom)>h4:first-child,.theme-default-content:not(.custom)>h5:first-child,.theme-default-content:not(.custom)>h6:first-child{margin-top:-1.5rem;margin-bottom:1rem}.theme-default-content:not(.custom)>h1:first-child+.custom-block,.theme-default-content:not(.custom)>h1:first-child+p,.theme-default-content:not(.custom)>h1:first-child+pre,.theme-default-content:not(.custom)>h2:first-child+.custom-block,.theme-default-content:not(.custom)>h2:first-child+p,.theme-default-content:not(.custom)>h2:first-child+pre,.theme-default-content:not(.custom)>h3:first-child+.custom-block,.theme-default-content:not(.custom)>h3:first-child+p,.theme-default-content:not(.custom)>h3:first-child+pre,.theme-default-content:not(.custom)>h4:first-child+.custom-block,.theme-default-content:not(.custom)>h4:first-child+p,.theme-default-content:not(.custom)>h4:first-child+pre,.theme-default-content:not(.custom)>h5:first-child+.custom-block,.theme-default-content:not(.custom)>h5:first-child+p,.theme-default-content:not(.custom)>h5:first-child+pre,.theme-default-content:not(.custom)>h6:first-child+.custom-block,.theme-default-content:not(.custom)>h6:first-child+p,.theme-default-content:not(.custom)>h6:first-child+pre{margin-top:2rem}h1:focus .header-anchor,h1:hover .header-anchor,h2:focus .header-anchor,h2:hover .header-anchor,h3:focus .header-anchor,h3:hover .header-anchor,h4:focus .header-anchor,h4:hover .header-anchor,h5:focus .header-anchor,h5:hover .header-anchor,h6:focus .header-anchor,h6:hover .header-anchor{opacity:1}h1{font-size:2.2rem}h2{font-size:1.65rem;padding-bottom:.3rem;border-bottom:1px solid #eaecef}h3{font-size:1.35rem}a.header-anchor{font-size:.85em;float:left;margin-left:-.87em;padding-right:.23em;margin-top:.125em;opacity:0}a.header-anchor:focus,a.header-anchor:hover{text-decoration:none}.line-number,code,kbd{font-family:source-code-pro,Menlo,Monaco,Consolas,Courier New,monospace}ol,p,ul{line-height:1.7}hr{border:0;border-top:1px solid #eaecef}table{border-collapse:collapse;margin:1rem 0;display:block;overflow-x:auto}tr{border-top:1px solid #dfe2e5}tr:nth-child(2n){background-color:#f6f8fa}td,th{border:1px solid #dfe2e5;padding:.6em 1em}.theme-container.sidebar-open .sidebar-mask{display:block}.theme-container.no-navbar .theme-default-content:not(.custom)>h1,.theme-container.no-navbar h2,.theme-container.no-navbar h3,.theme-container.no-navbar h4,.theme-container.no-navbar h5,.theme-container.no-navbar h6{margin-top:1.5rem;padding-top:0}.theme-container.no-navbar .sidebar{top:0}@media (min-width:720px){.theme-container.no-sidebar .sidebar{display:none}.theme-container.no-sidebar .page{padding-left:0}}@media (max-width:959px){.sidebar{font-size:15px;width:16.4rem}.page{padding-left:16.4rem}}@media (max-width:719px){.sidebar{top:0;padding-top:3.6rem;transform:translateX(-100%);transition:transform .2s ease}.page{padding-left:0}.theme-container.sidebar-open .sidebar{transform:translateX(0)}.theme-container.no-navbar .sidebar{padding-top:0}}@media (max-width:419px){h1{font-size:1.9rem}.theme-default-content div[class*=language-]{margin:.85rem -1.5rem;border-radius:0}}#nprogress{pointer-events:none}#nprogress .bar{background:#3eaf7c;position:fixed;z-index:1031;top:0;left:0;width:100%;height:2px}#nprogress .peg{display:block;position:absolute;right:0;width:100px;height:100%;box-shadow:0 0 10px #3eaf7c,0 0 5px #3eaf7c;opacity:1;transform:rotate(3deg) translateY(-4px)}#nprogress .spinner{display:block;position:fixed;z-index:1031;top:15px;right:15px}#nprogress .spinner-icon{width:18px;height:18px;box-sizing:border-box;border-color:#3eaf7c transparent transparent #3eaf7c;border-style:solid;border-width:2px;border-radius:50%;-webkit-animation:nprogress-spinner .4s linear infinite;animation:nprogress-spinner .4s linear infinite}.nprogress-custom-parent{overflow:hidden;position:relative}.nprogress-custom-parent #nprogress .bar,.nprogress-custom-parent #nprogress .spinner{position:absolute}@-webkit-keyframes nprogress-spinner{0%{transform:rotate(0deg)}to{transform:rotate(1turn)}}@keyframes nprogress-spinner{0%{transform:rotate(0deg)}to{transform:rotate(1turn)}}.icon.outbound{color:#aaa;display:inline-block;vertical-align:middle;position:relative;top:-1px}.sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border-width:0}@media screen and (max-width:1300px){.content__default:before{content:"";position:relative;display:block;padding:0 0 20px 30px;margin-top:20px;margin-right:-24px}}img{max-width:100%}.home{padding:3.6rem 2rem 0;max-width:960px;margin:0 auto;display:block}.home .hero{text-align:center}.home .hero img{max-width:100%;max-height:280px;display:block;margin:3rem auto 1.5rem}.home .hero h1{font-size:3rem}.home .hero .action,.home .hero .description,.home .hero h1{margin:1.8rem auto}.home .hero .description{max-width:35rem;font-size:1.6rem;line-height:1.3;color:#6a8bad}.home .hero .action-button{display:inline-block;font-size:1.2rem;color:#fff;background-color:#3eaf7c;padding:.8rem 1.6rem;border-radius:4px;transition:background-color .1s ease;box-sizing:border-box;border-bottom:1px solid #389d70}.home .hero .action-button:hover{background-color:#4abf8a}.home .features{border-top:1px solid #eaecef;padding:1.2rem 0;margin-top:2.5rem;display:flex;flex-wrap:wrap;align-items:flex-start;align-content:stretch;justify-content:space-between}.home .feature{flex-grow:1;flex-basis:30%;max-width:30%}.home .feature h2{font-size:1.4rem;font-weight:500;border-bottom:none;padding-bottom:0;color:#3a5169}.home .feature p{color:#4e6e8e}.home .footer{padding:2.5rem;border-top:1px solid #eaecef;text-align:center;color:#4e6e8e}@media (max-width:719px){.home .features{flex-direction:column}.home .feature{max-width:100%;padding:0 2.5rem}}@media (max-width:419px){.home{padding-left:1.5rem;padding-right:1.5rem}.home .hero img{max-height:210px;margin:2rem auto 1.2rem}.home .hero h1{font-size:2rem}.home .hero .action,.home .hero .description,.home .hero h1{margin:1.2rem auto}.home .hero .description{font-size:1.2rem}.home .hero .action-button{font-size:1rem;padding:.6rem 1.2rem}.home .feature h2{font-size:1.25rem}}.search-box{display:inline-block;position:relative;margin-right:1rem}.search-box input{cursor:text;width:10rem;height:2rem;color:#4e6e8e;display:inline-block;border:1px solid #cfd4db;border-radius:2rem;font-size:.9rem;line-height:2rem;padding:0 .5rem 0 2rem;outline:none;transition:all .2s ease;background:#fff url(/vue-i18n/assets/img/search.83621669.svg) .6rem .5rem no-repeat;background-size:1rem}.search-box input:focus{cursor:auto;border-color:#3eaf7c}.search-box .suggestions{background:#fff;width:20rem;position:absolute;top:2rem;border:1px solid #cfd4db;border-radius:6px;padding:.4rem;list-style-type:none}.search-box .suggestions.align-right{right:0}.search-box .suggestion{line-height:1.4;padding:.4rem .6rem;border-radius:4px;cursor:pointer}.search-box .suggestion a{white-space:normal;color:#5d82a6}.search-box .suggestion a .page-title{font-weight:600}.search-box .suggestion a .header{font-size:.9em;margin-left:.25em}.search-box .suggestion.focused{background-color:#f3f4f5}.search-box .suggestion.focused a{color:#3eaf7c}@media (max-width:959px){.search-box input{cursor:pointer;width:0;border-color:transparent;position:relative}.search-box input:focus{cursor:text;left:0;width:10rem}}@media (-ms-high-contrast:none){.search-box input{height:2rem}}@media (max-width:959px) and (min-width:719px){.search-box .suggestions{left:0}}@media (max-width:719px){.search-box{margin-right:0}.search-box input{left:1rem}.search-box .suggestions{right:0}}@media (max-width:419px){.search-box .suggestions{width:calc(100vw - 4rem)}.search-box input:focus{width:8rem}}.sidebar-button{cursor:pointer;display:none;width:1.25rem;height:1.25rem;position:absolute;padding:.6rem;top:.6rem;left:1rem}.sidebar-button .icon{display:block;width:1.25rem;height:1.25rem}@media (max-width:719px){.sidebar-button{display:block}}.dropdown-enter,.dropdown-leave-to{height:0!important}.dropdown-wrapper{cursor:pointer}.dropdown-wrapper .dropdown-title,.dropdown-wrapper .mobile-dropdown-title{display:block;font-size:.9rem;font-family:inherit;cursor:inherit;padding:inherit;line-height:1.4rem;background:transparent;border:none;font-weight:500;color:#2c3e50}.dropdown-wrapper .dropdown-title:hover,.dropdown-wrapper .mobile-dropdown-title:hover{border-color:transparent}.dropdown-wrapper .dropdown-title .arrow,.dropdown-wrapper .mobile-dropdown-title .arrow{vertical-align:middle;margin-top:-1px;margin-left:.4rem}.dropdown-wrapper .mobile-dropdown-title{display:none;font-weight:600}.dropdown-wrapper .mobile-dropdown-title font-size inherit:hover{color:#3eaf7c}.dropdown-wrapper .nav-dropdown .dropdown-item{color:inherit;line-height:1.7rem}.dropdown-wrapper .nav-dropdown .dropdown-item h4{margin:.45rem 0 0;border-top:1px solid #eee;padding:1rem 1.5rem .45rem 1.25rem}.dropdown-wrapper .nav-dropdown .dropdown-item .dropdown-subitem-wrapper{padding:0;list-style:none}.dropdown-wrapper .nav-dropdown .dropdown-item .dropdown-subitem-wrapper .dropdown-subitem{font-size:.9em}.dropdown-wrapper .nav-dropdown .dropdown-item a{display:block;line-height:1.7rem;position:relative;border-bottom:none;font-weight:400;margin-bottom:0;padding:0 1.5rem 0 1.25rem}.dropdown-wrapper .nav-dropdown .dropdown-item a.router-link-active,.dropdown-wrapper .nav-dropdown .dropdown-item a:hover{color:#3eaf7c}.dropdown-wrapper .nav-dropdown .dropdown-item a.router-link-active:after{content:"";width:0;height:0;border-left:5px solid #3eaf7c;border-top:3px solid transparent;border-bottom:3px solid transparent;position:absolute;top:calc(50% - 2px);left:9px}.dropdown-wrapper .nav-dropdown .dropdown-item:first-child h4{margin-top:0;padding-top:0;border-top:0}@media (max-width:719px){.dropdown-wrapper.open .dropdown-title{margin-bottom:.5rem}.dropdown-wrapper .dropdown-title{display:none}.dropdown-wrapper .mobile-dropdown-title{display:block}.dropdown-wrapper .nav-dropdown{transition:height .1s ease-out;overflow:hidden}.dropdown-wrapper .nav-dropdown .dropdown-item h4{border-top:0;margin-top:0;padding-top:0}.dropdown-wrapper .nav-dropdown .dropdown-item>a,.dropdown-wrapper .nav-dropdown .dropdown-item h4{font-size:15px;line-height:2rem}.dropdown-wrapper .nav-dropdown .dropdown-item .dropdown-subitem{font-size:14px;padding-left:1rem}}@media (min-width:719px){.dropdown-wrapper{height:1.8rem}.dropdown-wrapper.open .nav-dropdown,.dropdown-wrapper:hover .nav-dropdown{display:block!important}.dropdown-wrapper.open:blur{display:none}.dropdown-wrapper .nav-dropdown{display:none;height:auto!important;box-sizing:border-box;max-height:calc(100vh - 2.7rem);overflow-y:auto;position:absolute;top:100%;right:0;background-color:#fff;padding:.6rem 0;border:1px solid;border-color:#ddd #ddd #ccc;text-align:left;border-radius:.25rem;white-space:nowrap;margin:0}}.nav-links{display:inline-block}.nav-links a{line-height:1.4rem;color:inherit}.nav-links a.router-link-active,.nav-links a:hover{color:#3eaf7c}.nav-links .nav-item{position:relative;display:inline-block;margin-left:1.5rem;line-height:2rem}.nav-links .nav-item:first-child{margin-left:0}.nav-links .repo-link{margin-left:1.5rem}@media (max-width:719px){.nav-links .nav-item,.nav-links .repo-link{margin-left:0}}@media (min-width:719px){.nav-links a.router-link-active,.nav-links a:hover{color:#2c3e50}.nav-item>a:not(.external).router-link-active,.nav-item>a:not(.external):hover{margin-bottom:-2px;border-bottom:2px solid #46bd87}}.navbar{padding:.7rem 1.5rem;line-height:2.2rem}.navbar a,.navbar img,.navbar span{display:inline-block}.navbar .logo{height:2.2rem;min-width:2.2rem;margin-right:.8rem;vertical-align:top}.navbar .site-name{font-size:1.3rem;font-weight:600;color:#2c3e50;position:relative}.navbar .links{padding-left:1.5rem;box-sizing:border-box;background-color:#fff;white-space:nowrap;font-size:.9rem;position:absolute;right:1.5rem;top:.7rem;display:flex}.navbar .links .search-box{flex:0 0 auto;vertical-align:top}@media (max-width:719px){.navbar{padding-left:4rem}.navbar .can-hide{display:none}.navbar .links{padding-left:1.5rem}.navbar .site-name{width:calc(100vw - 9.4rem);overflow:hidden;white-space:nowrap;text-overflow:ellipsis}}.page-edit{max-width:740px;margin:0 auto;padding:2rem 2.5rem}@media (max-width:959px){.page-edit{padding:2rem}}@media (max-width:419px){.page-edit{padding:1.5rem}}.page-edit{padding-top:1rem;padding-bottom:1rem;overflow:auto}.page-edit .edit-link{display:inline-block}.page-edit .edit-link a{color:#4e6e8e;margin-right:.25rem}.page-edit .last-updated{float:right;font-size:.9em}.page-edit .last-updated .prefix{font-weight:500;color:#4e6e8e}.page-edit .last-updated .time{font-weight:400;color:#767676}@media (max-width:719px){.page-edit .edit-link{margin-bottom:.5rem}.page-edit .last-updated{font-size:.8em;float:none;text-align:left}}.page-nav{max-width:740px;margin:0 auto;padding:2rem 2.5rem}@media (max-width:959px){.page-nav{padding:2rem}}@media (max-width:419px){.page-nav{padding:1.5rem}}.page-nav{padding-top:1rem;padding-bottom:0}.page-nav .inner{min-height:2rem;margin-top:0;border-top:1px solid #eaecef;padding-top:1rem;overflow:auto}.page-nav .next{float:right}.page{padding-bottom:2rem;display:block}.sidebar-group .sidebar-group{padding-left:.5em}.sidebar-group:not(.collapsable) .sidebar-heading:not(.clickable){cursor:auto;color:inherit}.sidebar-group.is-sub-group{padding-left:0}.sidebar-group.is-sub-group>.sidebar-heading{font-size:.95em;line-height:1.4;font-weight:400;padding-left:2rem}.sidebar-group.is-sub-group>.sidebar-heading:not(.clickable){opacity:.5}.sidebar-group.is-sub-group>.sidebar-group-items{padding-left:1rem}.sidebar-group.is-sub-group>.sidebar-group-items>li>.sidebar-link{font-size:.95em;border-left:none}.sidebar-group.depth-2>.sidebar-heading{border-left:none}.sidebar-heading{color:#2c3e50;transition:color .15s ease;cursor:pointer;font-size:1.1em;font-weight:700;padding:.35rem 1.5rem .35rem 1.25rem;width:100%;box-sizing:border-box;margin:0;border-left:.25rem solid transparent}.sidebar-heading.open,.sidebar-heading:hover{color:inherit}.sidebar-heading .arrow{position:relative;top:-.12em;left:.5em}.sidebar-heading.clickable.active{font-weight:600;color:#3eaf7c;border-left-color:#3eaf7c}.sidebar-heading.clickable:hover{color:#3eaf7c}.sidebar-group-items{transition:height .1s ease-out;font-size:.95em;overflow:hidden}.sidebar .sidebar-sub-headers{padding-left:1rem;font-size:.95em}a.sidebar-link{font-size:1em;font-weight:400;display:inline-block;color:#2c3e50;border-left:.25rem solid transparent;padding:.35rem 1rem .35rem 1.25rem;line-height:1.4;width:100%;box-sizing:border-box}a.sidebar-link:hover{color:#3eaf7c}a.sidebar-link.active{font-weight:600;color:#3eaf7c;border-left-color:#3eaf7c}.sidebar-group a.sidebar-link{padding-left:2rem}.sidebar-sub-headers a.sidebar-link{padding-top:.25rem;padding-bottom:.25rem;border-left:none}.sidebar-sub-headers a.sidebar-link.active{font-weight:500}.sidebar ul{padding:0;margin:0;list-style-type:none}.sidebar a{display:inline-block}.sidebar .nav-links{display:none;border-bottom:1px solid #eaecef;padding:.5rem 0 .75rem}.sidebar .nav-links a{font-weight:600}.sidebar .nav-links .nav-item,.sidebar .nav-links .repo-link{display:block;line-height:1.25rem;font-size:1.1em;padding:.5rem 0 .5rem 1.5rem}.sidebar>.sidebar-links{padding:1.5rem 0}.sidebar>.sidebar-links>li>a.sidebar-link{font-size:1.1em;line-height:1.7;font-weight:700}.sidebar>.sidebar-links>li:not(:first-child){margin-top:.75rem}@media (max-width:719px){.sidebar .nav-links{display:block}.sidebar .nav-links .dropdown-wrapper .nav-dropdown .dropdown-item a.router-link-active:after{top:calc(1rem - 2px)}.sidebar>.sidebar-links{padding:1rem 0}}.carbon-ads{min-height:102px;font-size:.75rem;position:relative;z-index:1;top:87px;right:0;max-width:740px;margin:0 auto;padding:2rem 2.5rem!important;background-color:#fff;border-radius:3px;font-size:13px}@media screen and (max-width:1300px){.carbon-ads{position:relative;top:87px;right:0;padding:2rem 2.5rem!important;max-width:740px;margin:0 auto;padding:2rem 2.5rem}}.carbon-ads a{color:#444;font-weight:400;display:inline}.carbon-ads .carbon-img{float:left;margin-right:1rem;border:1px solid var(--border-color)}.carbon-ads .carbon-img img{display:block}.carbon-ads .carbon-poweredby{color:#999;display:block;margin-top:.5em}@media (max-width:719px){.carbon-ads .carbon-img img{width:100px;height:77px}}@media (min-width:320px) and (max-width:759px){.carbon-ads{left:1.5rem!important;padding:.5rem!important}}.sponsor-button[data-v-0a314292]{text-align:center;margin:24px 0}.badge[data-v-15b7b770]{display:inline-block;font-size:14px;height:18px;line-height:18px;border-radius:3px;padding:0 6px;color:#fff}.badge.green[data-v-15b7b770],.badge.tip[data-v-15b7b770],.badge[data-v-15b7b770]{background-color:#42b983}.badge.error[data-v-15b7b770]{background-color:#da5961}.badge.warn[data-v-15b7b770],.badge.warning[data-v-15b7b770],.badge.yellow[data-v-15b7b770]{background-color:#e7c000}.badge+.badge[data-v-15b7b770]{margin-left:5px}.theme-code-block[data-v-759a7d02]{display:none}.theme-code-block__active[data-v-759a7d02]{display:block}.theme-code-block>pre[data-v-759a7d02]{background-color:orange}.theme-code-group__nav[data-v-deefee04]{margin-bottom:-35px;background-color:#282c34;padding-bottom:22px;border-top-left-radius:6px;border-top-right-radius:6px;padding-left:10px;padding-top:10px}.theme-code-group__ul[data-v-deefee04]{margin:auto 0;padding-left:0;display:inline-flex;list-style:none}.theme-code-group__nav-tab[data-v-deefee04]{border:0;padding:5px;cursor:pointer;background-color:transparent;font-size:.85em;line-height:1.4;color:hsla(0,0%,100%,.9);font-weight:600}.theme-code-group__nav-tab-active[data-v-deefee04]{border-bottom:1px solid #42b983}.pre-blank[data-v-deefee04]{color:#42b983} \ No newline at end of file diff --git a/assets/img/search.83621669.svg b/assets/img/search.83621669.svg new file mode 100644 index 000000000..03d83913e --- /dev/null +++ b/assets/img/search.83621669.svg @@ -0,0 +1 @@ + diff --git a/assets/js/10.c1277640.js b/assets/js/10.c1277640.js new file mode 100644 index 000000000..0af61cba3 --- /dev/null +++ b/assets/js/10.c1277640.js @@ -0,0 +1 @@ +(window.webpackJsonp=window.webpackJsonp||[]).push([[10],{462:function(t,e,a){"use strict";a.r(e);var s=a(44),o=Object(s.a)({},(function(){var t=this,e=t.$createElement,a=t._self._c||e;return a("ContentSlotsDistributor",{attrs:{"slot-key":t.$parent.slotKey}},[a("h1",{attrs:{id:"api-references"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#api-references"}},[t._v("#")]),t._v(" API references")]),t._v(" "),a("h2",{attrs:{id:"extension-of-vue"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#extension-of-vue"}},[t._v("#")]),t._v(" Extension of Vue")]),t._v(" "),a("h3",{attrs:{id:"vue-constructor-options"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#vue-constructor-options"}},[t._v("#")]),t._v(" Vue constructor options")]),t._v(" "),a("h4",{attrs:{id:"i18n"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#i18n"}},[t._v("#")]),t._v(" i18n")]),t._v(" "),a("ul",[a("li",[a("strong",[t._v("Type:")]),t._v(" "),a("code",[t._v("I18nOptions")])])]),t._v(" "),a("p",[t._v("Component based localization option.")]),t._v(" "),a("ul",[a("li",[a("strong",[t._v("See also:")]),t._v(" "),a("code",[t._v("VueI18n")]),t._v(" class constructor options")])]),t._v(" "),a("h3",{attrs:{id:"vue-injected-methods"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#vue-injected-methods"}},[t._v("#")]),t._v(" Vue injected methods")]),t._v(" "),a("h4",{attrs:{id:"t"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#t"}},[t._v("#")]),t._v(" $t")]),t._v(" "),a("ul",[a("li",[a("p",[a("strong",[t._v("Arguments:")])]),t._v(" "),a("ul",[a("li",[a("code",[t._v("{Path} key")]),t._v(": required")]),t._v(" "),a("li",[a("code",[t._v("{Locale} locale")]),t._v(": optional")]),t._v(" "),a("li",[a("code",[t._v("{Array | Object} values")]),t._v(": optional")])])]),t._v(" "),a("li",[a("p",[a("strong",[t._v("Return:")]),t._v(" "),a("code",[t._v("TranslateResult")])])])]),t._v(" "),a("p",[t._v("Localize the locale message of "),a("code",[t._v("key")]),t._v(". Localize in preferentially component locale messages than global locale messages. If not specified component locale messages, localize with global locale messages. If you specified "),a("code",[t._v("locale")]),t._v(", localize the locale messages of "),a("code",[t._v("locale")]),t._v(". If you specified "),a("code",[t._v("key")]),t._v(" of list / named formatting local messages, you must specify "),a("code",[t._v("values")]),t._v(" too. For "),a("code",[t._v("values")]),t._v(" more details see "),a("RouterLink",{attrs:{to:"/guide/formatting.html"}},[t._v("Formatting")]),t._v(".")],1),t._v(" "),a("p",[t._v("If default pluralization does not suit your needs, see "),a("a",{attrs:{href:"#pluralizationrules"}},[t._v("pluralization rules in constructor options")]),t._v(" and "),a("RouterLink",{attrs:{to:"/guide/pluralization.html"}},[t._v("custom pluralization")]),t._v(".")],1),t._v(" "),a("div",{staticClass:"custom-block danger"},[a("p",{staticClass:"custom-block-title"},[t._v("Tip")]),t._v(" "),a("p",[t._v("Note that you need to guarantee this context equal to component instance in lifecycle methods (e.g. in "),a("code",[t._v("data")]),t._v(" options, "),a("code",[t._v("const $t = this.$t.bind(this)")]),t._v(").")])]),t._v(" "),a("h4",{attrs:{id:"tc"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#tc"}},[t._v("#")]),t._v(" $tc")]),t._v(" "),a("ul",[a("li",[a("p",[a("strong",[t._v("Arguments:")])]),t._v(" "),a("ul",[a("li",[a("code",[t._v("{Path} key")]),t._v(": required")]),t._v(" "),a("li",[a("code",[t._v("{number} choice")]),t._v(": optional, default 1")]),t._v(" "),a("li",[a("code",[t._v("{Locale} locale")]),t._v(": optional")]),t._v(" "),a("li",[a("code",[t._v("{string | Array | Object} values")]),t._v(": optional")])])]),t._v(" "),a("li",[a("p",[a("strong",[t._v("Return:")]),t._v(" "),a("code",[t._v("TranslateResult")])])])]),t._v(" "),a("p",[t._v("Localize the locale message of "),a("code",[t._v("key")]),t._v(" with pluralization. Localize in preferentially component locale messages than global locale messages. If not specified component locale messages, localize with global locale messages. If you specified "),a("code",[t._v("locale")]),t._v(", localize the locale messages of "),a("code",[t._v("locale")]),t._v(". If you will specify string value to "),a("code",[t._v("values")]),t._v(", localize the locale messages of value. If you will specify Array or Object value to "),a("code",[t._v("values")]),t._v(", you must specify with "),a("code",[t._v("values")]),t._v(" of $t.")]),t._v(" "),a("div",{staticClass:"custom-block danger"},[a("p",{staticClass:"custom-block-title"},[t._v("Tip")]),t._v(" "),a("p",[t._v("Note that you need to guarantee this context equal to component instance in lifecycle methods (e.g. in "),a("code",[t._v("data")]),t._v(" options, "),a("code",[t._v("const $tc = this.$tc.bind(this)")]),t._v(").")])]),t._v(" "),a("h4",{attrs:{id:"te"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#te"}},[t._v("#")]),t._v(" $te")]),t._v(" "),a("ul",[a("li",[a("p",[a("strong",[t._v("Arguments:")])]),t._v(" "),a("ul",[a("li",[a("code",[t._v("{Path} key")]),t._v(": required")]),t._v(" "),a("li",[a("code",[t._v("{Locale} locale")]),t._v(": optional")])])]),t._v(" "),a("li",[a("p",[a("strong",[t._v("Return:")]),t._v(" "),a("code",[t._v("boolean")])])])]),t._v(" "),a("p",[t._v("Check whether key exists. In Vue instance, If not specified component locale messages, check with global locale messages. If you specified "),a("code",[t._v("locale")]),t._v(", check the locale messages of "),a("code",[t._v("locale")]),t._v(".")]),t._v(" "),a("div",{staticClass:"custom-block danger"},[a("p",{staticClass:"custom-block-title"},[t._v("Tip")]),t._v(" "),a("p",[t._v("Note that you need to guarantee this context equal to component instance in lifecycle methods (e.g. in "),a("code",[t._v("data")]),t._v(" options, "),a("code",[t._v("const $te = this.$te.bind(this)")]),t._v(").")])]),t._v(" "),a("h4",{attrs:{id:"d"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#d"}},[t._v("#")]),t._v(" $d")]),t._v(" "),a("blockquote",[a("p",[t._v("🆕 7.0+")])]),t._v(" "),a("ul",[a("li",[a("p",[a("strong",[t._v("Arguments:")])]),t._v(" "),a("ul",[a("li",[a("code",[t._v("{number | Date} value")]),t._v(": required")]),t._v(" "),a("li",[a("code",[t._v("{Path | Object} key")]),t._v(": optional")]),t._v(" "),a("li",[a("code",[t._v("{Locale | Object} locale")]),t._v(": optional")])])]),t._v(" "),a("li",[a("p",[a("strong",[t._v("Return:")]),t._v(" "),a("code",[t._v("DateTimeFormatResult")])])])]),t._v(" "),a("p",[t._v("Localize the datetime of "),a("code",[t._v("value")]),t._v(" with datetime format of "),a("code",[t._v("key")]),t._v(". The datetime format of "),a("code",[t._v("key")]),t._v(" need to register to "),a("code",[t._v("dateTimeFormats")]),t._v(" option of "),a("code",[t._v("VueI18n")]),t._v(" class, and depend on "),a("code",[t._v("locale")]),t._v(" option of "),a("code",[t._v("VueI18n")]),t._v(" constructor. If you will specify "),a("code",[t._v("locale")]),t._v(" argument, it will have priority over "),a("code",[t._v("locale")]),t._v(" option of "),a("code",[t._v("VueI18n")]),t._v(" constructor.")]),t._v(" "),a("p",[t._v("If the datetime format of "),a("code",[t._v("key")]),t._v(" not exist in "),a("code",[t._v("dateTimeFormats")]),t._v(" option, fallback to depend on "),a("code",[t._v("fallbackLocale")]),t._v(" option of "),a("code",[t._v("VueI18n")]),t._v(" constructor.")]),t._v(" "),a("div",{staticClass:"custom-block danger"},[a("p",{staticClass:"custom-block-title"},[t._v("Tip")]),t._v(" "),a("p",[t._v("Note that you need to guarantee this context equal to component instance in lifecycle methods (e.g. in "),a("code",[t._v("data")]),t._v(" options, "),a("code",[t._v("const $d = this.$d.bind(this)")]),t._v(").")])]),t._v(" "),a("h4",{attrs:{id:"n"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#n"}},[t._v("#")]),t._v(" $n")]),t._v(" "),a("blockquote",[a("p",[t._v("🆕 7.0+")])]),t._v(" "),a("ul",[a("li",[a("p",[a("strong",[t._v("Arguments:")])]),t._v(" "),a("ul",[a("li",[a("code",[t._v("{number} value")]),t._v(": required")]),t._v(" "),a("li",[a("code",[t._v("{Path | Object} format")]),t._v(": optional")]),t._v(" "),a("li",[a("code",[t._v("{Locale} locale")]),t._v(": optional")])])]),t._v(" "),a("li",[a("p",[a("strong",[t._v("Return:")]),t._v(" "),a("code",[t._v("NumberFormatResult")])])])]),t._v(" "),a("p",[t._v("Localize the number of "),a("code",[t._v("value")]),t._v(" with number format of "),a("code",[t._v("format")]),t._v(". The number format of "),a("code",[t._v("format")]),t._v(" need to register to "),a("code",[t._v("numberFormats")]),t._v(" option of "),a("code",[t._v("VueI18n")]),t._v(" class, and depend on "),a("code",[t._v("locale")]),t._v(" option of "),a("code",[t._v("VueI18n")]),t._v(" constructor. If you will specify "),a("code",[t._v("locale")]),t._v(" argument, it will have priority over "),a("code",[t._v("locale")]),t._v(" option of "),a("code",[t._v("VueI18n")]),t._v(" constructor.")]),t._v(" "),a("p",[t._v("If the number format of "),a("code",[t._v("format")]),t._v(" not exist in "),a("code",[t._v("numberFormats")]),t._v(" option, fallback to depend on "),a("code",[t._v("fallbackLocale")]),t._v(" option of "),a("code",[t._v("VueI18n")]),t._v(" constructor.")]),t._v(" "),a("p",[t._v("If the second "),a("code",[t._v("format")]),t._v(" argument specified as an object, it should have the following properties:")]),t._v(" "),a("ul",[a("li",[a("code",[t._v("key {Path}")]),t._v(": optional, number format")]),t._v(" "),a("li",[a("code",[t._v("locale {Locale}")]),t._v(": optional, locale")]),t._v(" "),a("li",[a("code",[t._v("compactDisplay {string}")]),t._v(": optional, number format option")]),t._v(" "),a("li",[a("code",[t._v("currency {string}")]),t._v(": optional, number format option")]),t._v(" "),a("li",[a("code",[t._v("currencyDisplay {string}")]),t._v(": optional, number format option")]),t._v(" "),a("li",[a("code",[t._v("currencySign {string}")]),t._v(": optional, number format option")]),t._v(" "),a("li",[a("code",[t._v("localeMatcher {string}")]),t._v(": optional, number format option")]),t._v(" "),a("li",[a("code",[t._v("notation {string}")]),t._v(": optional, number format option")]),t._v(" "),a("li",[a("code",[t._v("numberingSystem {string}")]),t._v(": optional, number format option")]),t._v(" "),a("li",[a("code",[t._v("signDisplay {string}")]),t._v(": optional, number format option")]),t._v(" "),a("li",[a("code",[t._v("style {string}")]),t._v(": optional, number format option")]),t._v(" "),a("li",[a("code",[t._v("unit {string}")]),t._v(": optional, number format option")]),t._v(" "),a("li",[a("code",[t._v("unitDisplay {string}")]),t._v(": optional, number format option")]),t._v(" "),a("li",[a("code",[t._v("useGrouping {boolean}")]),t._v(": optional, number format option")]),t._v(" "),a("li",[a("code",[t._v("minimumIntegerDigits {string}")]),t._v(": optional, number format option")]),t._v(" "),a("li",[a("code",[t._v("minimumFractionDigits {string}")]),t._v(": optional, number format option")]),t._v(" "),a("li",[a("code",[t._v("maximumFractionDigits {string}")]),t._v(": optional, number format option")]),t._v(" "),a("li",[a("code",[t._v("minimumSignificantDigits {string}")]),t._v(": optional, number format option")]),t._v(" "),a("li",[a("code",[t._v("maximumSignificantDigits {string}")]),t._v(": optional, number format option")])]),t._v(" "),a("p",[t._v("Any specified number format options will have priority over "),a("code",[t._v("numberFormats")]),t._v(" of "),a("code",[t._v("VueI18n")]),t._v(" constructor.")]),t._v(" "),a("div",{staticClass:"custom-block danger"},[a("p",{staticClass:"custom-block-title"},[t._v("Tip")]),t._v(" "),a("p",[t._v("Note that you need to guarantee this context equal to component instance in lifecycle methods (e.g. in "),a("code",[t._v("data")]),t._v(" options, "),a("code",[t._v("const $n = this.$n.bind(this)")]),t._v(").")])]),t._v(" "),a("h3",{attrs:{id:"injected-properties"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#injected-properties"}},[t._v("#")]),t._v(" Injected properties")]),t._v(" "),a("h4",{attrs:{id:"i18n-2"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#i18n-2"}},[t._v("#")]),t._v(" $i18n")]),t._v(" "),a("ul",[a("li",[a("p",[a("strong",[t._v("Type:")]),t._v(" "),a("code",[t._v("I18n")])])]),t._v(" "),a("li",[a("p",[a("strong",[t._v("Read only")])])])]),t._v(" "),a("p",[t._v("Get a "),a("code",[t._v("VueI18n")]),t._v(" instance. If you are specify.")]),t._v(" "),a("p",[t._v("If you have specified an "),a("code",[t._v("i18n")]),t._v(" option at component options, you will be able to get a "),a("code",[t._v("VueI18n")]),t._v(" instance at the component, Otherwise, you will be able get root "),a("code",[t._v("VueI18n")]),t._v(" instance.")]),t._v(" "),a("h2",{attrs:{id:"vuei18n-class"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#vuei18n-class"}},[t._v("#")]),t._v(" "),a("code",[t._v("VueI18n")]),t._v(" class")]),t._v(" "),a("p",[a("code",[t._v("VueI18n")]),t._v(" class implement "),a("code",[t._v("I18n")]),t._v(" interface of "),a("a",{attrs:{href:"https://github.com/kazupon/vue-i18n/blob/dev/decls/i18n.js",target:"_blank",rel:"noopener noreferrer"}},[t._v("flowtype definitions"),a("OutboundLink")],1)]),t._v(" "),a("h3",{attrs:{id:"static-properties"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#static-properties"}},[t._v("#")]),t._v(" Static properties")]),t._v(" "),a("h4",{attrs:{id:"version"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#version"}},[t._v("#")]),t._v(" version")]),t._v(" "),a("ul",[a("li",[a("strong",[t._v("Type:")]),t._v(" "),a("code",[t._v("string")])])]),t._v(" "),a("p",[t._v("vue-i18n version.")]),t._v(" "),a("h4",{attrs:{id:"availabilities"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#availabilities"}},[t._v("#")]),t._v(" availabilities")]),t._v(" "),a("blockquote",[a("p",[t._v("🆕 7.0+")])]),t._v(" "),a("ul",[a("li",[a("strong",[t._v("Type:")]),t._v(" "),a("code",[t._v("IntlAvailability")])])]),t._v(" "),a("p",[t._v("Whether the following internationalization features are available:")]),t._v(" "),a("ul",[a("li",[a("p",[a("code",[t._v("{boolean} dateTimeFormat")]),t._v(": locale sensitive datetime formatting")])]),t._v(" "),a("li",[a("p",[a("code",[t._v("{boolean} numberFormat")]),t._v(": locale sensitive number formatting")])])]),t._v(" "),a("p",[t._v("The above internationalization features are depends on "),a("a",{attrs:{href:"http://kangax.github.io/compat-table/esintl/",target:"_blank",rel:"noopener noreferrer"}},[t._v("the browser environments"),a("OutboundLink")],1),t._v(", due to implement with ECMAScript Internationalization API (ECMA-402).")]),t._v(" "),a("h3",{attrs:{id:"constructor-options"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#constructor-options"}},[t._v("#")]),t._v(" Constructor options")]),t._v(" "),a("p",[t._v("You can specify the below some options of "),a("code",[t._v("I18nOptions")]),t._v(" constructor options of "),a("a",{attrs:{href:"https://github.com/kazupon/vue-i18n/blob/dev/decls/i18n.js",target:"_blank",rel:"noopener noreferrer"}},[t._v("flowtype definitions"),a("OutboundLink")],1)]),t._v(" "),a("h4",{attrs:{id:"locale"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#locale"}},[t._v("#")]),t._v(" locale")]),t._v(" "),a("ul",[a("li",[a("p",[a("strong",[t._v("Type:")]),t._v(" "),a("code",[t._v("Locale")])])]),t._v(" "),a("li",[a("p",[a("strong",[t._v("Default:")]),t._v(" "),a("code",[t._v("'en-US'")])])])]),t._v(" "),a("p",[t._v("The locale of localization. If the locale contains a territory and a dialect, this locale contains an implicit fallback.")]),t._v(" "),a("h4",{attrs:{id:"fallbacklocale"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#fallbacklocale"}},[t._v("#")]),t._v(" fallbackLocale")]),t._v(" "),a("ul",[a("li",[a("p",[a("strong",[t._v("Type:")]),t._v(" "),a("code",[t._v("FallbackLocale")])])]),t._v(" "),a("li",[a("p",[a("strong",[t._v("Default:")]),t._v(" "),a("code",[t._v("false")])])])]),t._v(" "),a("p",[t._v("The locale of fallback localization. For more complex fallback definitions see "),a("RouterLink",{attrs:{to:"/guide/fallback.html"}},[t._v("fallback")]),t._v(".")],1),t._v(" "),a("h4",{attrs:{id:"messages"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#messages"}},[t._v("#")]),t._v(" messages")]),t._v(" "),a("ul",[a("li",[a("p",[a("strong",[t._v("Type:")]),t._v(" "),a("code",[t._v("LocaleMessages")])])]),t._v(" "),a("li",[a("p",[a("strong",[t._v("Default:")]),t._v(" "),a("code",[t._v("{}")])])])]),t._v(" "),a("p",[t._v("The locale messages of localization.")]),t._v(" "),a("h4",{attrs:{id:"datetimeformats"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#datetimeformats"}},[t._v("#")]),t._v(" dateTimeFormats")]),t._v(" "),a("blockquote",[a("p",[t._v("🆕 7.0+")])]),t._v(" "),a("ul",[a("li",[a("p",[a("strong",[t._v("Type:")]),t._v(" "),a("code",[t._v("DateTimeFormats")])])]),t._v(" "),a("li",[a("p",[a("strong",[t._v("Default:")]),t._v(" "),a("code",[t._v("{}")])])])]),t._v(" "),a("p",[t._v("The datetime formats of localization.")]),t._v(" "),a("ul",[a("li",[a("strong",[t._v("See also:")]),t._v(" "),a("code",[t._v("DateTimeFormats")]),t._v(" type of "),a("a",{attrs:{href:"https://github.com/kazupon/vue-i18n/blob/dev/decls/i18n.js",target:"_blank",rel:"noopener noreferrer"}},[t._v("flowtype definitions"),a("OutboundLink")],1)])]),t._v(" "),a("h4",{attrs:{id:"numberformats"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#numberformats"}},[t._v("#")]),t._v(" numberFormats")]),t._v(" "),a("blockquote",[a("p",[t._v("🆕 7.0+")])]),t._v(" "),a("ul",[a("li",[a("p",[a("strong",[t._v("Type:")]),t._v(" "),a("code",[t._v("NumberFormats")])])]),t._v(" "),a("li",[a("p",[a("strong",[t._v("Default:")]),t._v(" "),a("code",[t._v("{}")])])])]),t._v(" "),a("p",[t._v("The number formats of localization.")]),t._v(" "),a("ul",[a("li",[a("strong",[t._v("See also:")]),t._v(" "),a("code",[t._v("NumberFormats")]),t._v(" type of "),a("a",{attrs:{href:"https://github.com/kazupon/vue-i18n/blob/dev/decls/i18n.js",target:"_blank",rel:"noopener noreferrer"}},[t._v("flowtype definitions"),a("OutboundLink")],1)])]),t._v(" "),a("h4",{attrs:{id:"formatter"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#formatter"}},[t._v("#")]),t._v(" formatter")]),t._v(" "),a("ul",[a("li",[a("p",[a("strong",[t._v("Type:")]),t._v(" "),a("code",[t._v("Formatter")])])]),t._v(" "),a("li",[a("p",[a("strong",[t._v("Default:")]),t._v(" Built in formatter")])])]),t._v(" "),a("p",[t._v("The formatter that implemented with "),a("code",[t._v("Formatter")]),t._v(" interface.")]),t._v(" "),a("h4",{attrs:{id:"modifiers"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#modifiers"}},[t._v("#")]),t._v(" modifiers")]),t._v(" "),a("blockquote",[a("p",[t._v("🆕 8.15.0+")])]),t._v(" "),a("ul",[a("li",[a("p",[a("strong",[t._v("Type:")]),t._v(" "),a("code",[t._v("Modifiers")])])]),t._v(" "),a("li",[a("p",[a("strong",[t._v("Default:")]),t._v(" "),a("code",[t._v("lower")]),t._v(" and "),a("code",[t._v("upper")]),t._v(" modifiers")])])]),t._v(" "),a("p",[t._v("Modifiers functions for linked messages")]),t._v(" "),a("h4",{attrs:{id:"missing"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#missing"}},[t._v("#")]),t._v(" missing")]),t._v(" "),a("ul",[a("li",[a("p",[a("strong",[t._v("Type:")]),t._v(" "),a("code",[t._v("MissingHandler")])])]),t._v(" "),a("li",[a("p",[a("strong",[t._v("Default:")]),t._v(" "),a("code",[t._v("null")])])])]),t._v(" "),a("p",[t._v("A handler for localization missing. The handler gets called with the localization target locale, localization path key, the Vue instance and values.")]),t._v(" "),a("p",[t._v("If missing handler is assigned, and occurred localization missing, it's not warned.")]),t._v(" "),a("h4",{attrs:{id:"fallbackroot"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#fallbackroot"}},[t._v("#")]),t._v(" fallbackRoot")]),t._v(" "),a("ul",[a("li",[a("p",[a("strong",[t._v("Type:")]),t._v(" "),a("code",[t._v("Boolean")])])]),t._v(" "),a("li",[a("p",[a("strong",[t._v("Default:")]),t._v(" "),a("code",[t._v("true")])])])]),t._v(" "),a("p",[t._v("In the component localization, whether to fall back to root level (global) localization when localization fails.")]),t._v(" "),a("p",[t._v("If "),a("code",[t._v("false")]),t._v(", it's warned, and is returned the key.")]),t._v(" "),a("h4",{attrs:{id:"fallbackrootwithemptystring"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#fallbackrootwithemptystring"}},[t._v("#")]),t._v(" fallbackRootWithEmptyString")]),t._v(" "),a("blockquote",[a("p",[t._v("🆕 8.26+")])]),t._v(" "),a("ul",[a("li",[a("p",[a("strong",[t._v("Type:")]),t._v(" "),a("code",[t._v("Boolean")])])]),t._v(" "),a("li",[a("p",[a("strong",[t._v("Default:")]),t._v(" "),a("code",[t._v("true")])]),t._v(" "),a("p",[t._v("In the component localization, whether to fall back to root level (global) localization when local message is an empty string.")]),t._v(" "),a("p",[t._v("Please note the default behavior in vue-i18n 9.x is to not falling back to root for local message that is empty string.")]),t._v(" "),a("p",[t._v("If "),a("code",[t._v("false")]),t._v(", the empty local message will not fall back to root and will be kept as empty string.")])])]),t._v(" "),a("h4",{attrs:{id:"sync"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#sync"}},[t._v("#")]),t._v(" sync")]),t._v(" "),a("ul",[a("li",[a("p",[a("strong",[t._v("Type:")]),t._v(" "),a("code",[t._v("Boolean")])])]),t._v(" "),a("li",[a("p",[a("strong",[t._v("Default:")]),t._v(" "),a("code",[t._v("true")])])])]),t._v(" "),a("p",[t._v("Whether synchronize the root level locale to the component localization locale.")]),t._v(" "),a("p",[t._v("If "),a("code",[t._v("false")]),t._v(", regardless of the root level locale, localize for each component locale.")]),t._v(" "),a("h4",{attrs:{id:"silenttranslationwarn"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#silenttranslationwarn"}},[t._v("#")]),t._v(" silentTranslationWarn")]),t._v(" "),a("blockquote",[a("p",[t._v("6.1+, 🆙 8.13")])]),t._v(" "),a("ul",[a("li",[a("p",[a("strong",[t._v("Type:")]),t._v(" "),a("code",[t._v("Boolean | RegExp")])])]),t._v(" "),a("li",[a("p",[a("strong",[t._v("Default:")]),t._v(" "),a("code",[t._v("false")])])])]),t._v(" "),a("p",[t._v("Whether suppress warnings outputted when localization fails.")]),t._v(" "),a("p",[t._v("If "),a("code",[t._v("true")]),t._v(", suppress localization fail warnings.\nIf you use regular expression, you can suppress localization fail warnings that it match with translation "),a("code",[t._v("key")]),t._v(" (e.g. "),a("code",[t._v("$t")]),t._v(").")]),t._v(" "),a("h4",{attrs:{id:"silentfallbackwarn"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#silentfallbackwarn"}},[t._v("#")]),t._v(" silentFallbackWarn")]),t._v(" "),a("blockquote",[a("p",[t._v("🆕 8.8+, 🆙 8.13")])]),t._v(" "),a("ul",[a("li",[a("strong",[t._v("Type:")]),t._v(" "),a("code",[t._v("Boolean | RegExp")])]),t._v(" "),a("li",[a("strong",[t._v("Default:")]),t._v(" "),a("code",[t._v("false")])])]),t._v(" "),a("p",[t._v("Whether suppress warnings when falling back to either "),a("code",[t._v("fallbackLocale")]),t._v(" or "),a("code",[t._v("root")]),t._v(".")]),t._v(" "),a("p",[t._v("If "),a("code",[t._v("true")]),t._v(", warnings will be generated only when no translation is available at all, and not for fallbacks.\nIf you use regular expression, you can suppress the fallback warnings that it match "),a("code",[t._v("key")]),t._v(" (e.g. "),a("code",[t._v("$t")]),t._v(").")]),t._v(" "),a("h4",{attrs:{id:"pluralizationrules"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#pluralizationrules"}},[t._v("#")]),t._v(" pluralizationRules")]),t._v(" "),a("blockquote",[a("p",[t._v("8.5+")])]),t._v(" "),a("ul",[a("li",[a("p",[a("strong",[t._v("Type:")]),t._v(" "),a("code",[t._v("PluralizationRules")])])]),t._v(" "),a("li",[a("p",[a("strong",[t._v("Default:")]),t._v(" "),a("code",[t._v("{}")])])])]),t._v(" "),a("p",[t._v("A set of rules for word pluralization in a following format:")]),t._v(" "),a("div",{staticClass:"language-js extra-class"},[a("pre",{pre:!0,attrs:{class:"language-js"}},[a("code",[t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// Key - locale for the rule to be applied to.")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// Value - mapping function that maps a choice index from `$tc` to the actual choice of the plural word. (See getChoiceIndex for details)")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token string-property property"}},[t._v("'pt'")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("function")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),a("span",{pre:!0,attrs:{class:"token parameter"}},[t._v("choice"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" choiceIndex")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=>")]),t._v(" Number"),a("span",{pre:!0,attrs:{class:"token comment"}},[t._v("/* index of the plural word */")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token string-property property"}},[t._v("'ru'")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("function")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),a("span",{pre:!0,attrs:{class:"token parameter"}},[t._v("choice"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" choiceIndex")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=>")]),t._v(" Number"),a("span",{pre:!0,attrs:{class:"token comment"}},[t._v("/* index of the plural word */")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token string-property property"}},[t._v("'en'")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("function")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),a("span",{pre:!0,attrs:{class:"token parameter"}},[t._v("choice"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" choiceIndex")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=>")]),t._v(" Number"),a("span",{pre:!0,attrs:{class:"token comment"}},[t._v("/* index of the plural word */")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token string-property property"}},[t._v("'jp'")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("function")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),a("span",{pre:!0,attrs:{class:"token parameter"}},[t._v("choice"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" choiceIndex")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=>")]),t._v(" Number"),a("span",{pre:!0,attrs:{class:"token comment"}},[t._v("/* index of the plural word */")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n")])])]),a("h4",{attrs:{id:"preservedirectivecontent"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#preservedirectivecontent"}},[t._v("#")]),t._v(" preserveDirectiveContent")]),t._v(" "),a("blockquote",[a("p",[t._v("8.7+")])]),t._v(" "),a("ul",[a("li",[a("p",[a("strong",[t._v("Type:")]),t._v(" "),a("code",[t._v("Boolean")])])]),t._v(" "),a("li",[a("p",[a("strong",[t._v("Default:")]),t._v(" "),a("code",[t._v("false")])])])]),t._v(" "),a("p",[t._v("Whether "),a("code",[t._v("v-t")]),t._v(" directive's element should preserve "),a("code",[t._v("textContent")]),t._v(" after directive is unbinded.")]),t._v(" "),a("h4",{attrs:{id:"warnhtmlinmessage"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#warnhtmlinmessage"}},[t._v("#")]),t._v(" warnHtmlInMessage")]),t._v(" "),a("blockquote",[a("p",[t._v("8.11+")])]),t._v(" "),a("ul",[a("li",[a("p",[a("strong",[t._v("Type:")]),t._v(" "),a("code",[t._v("WarnHtmlInMessageLevel")])])]),t._v(" "),a("li",[a("p",[a("strong",[t._v("Default:")]),t._v(" "),a("code",[t._v("off")])])])]),t._v(" "),a("p",[t._v("Whether to allow the use locale messages of HTML formatting. See the "),a("code",[t._v("warnHtmlInMessage")]),t._v(" property.")]),t._v(" "),a("div",{staticClass:"custom-block danger"},[a("p",{staticClass:"custom-block-title"},[t._v("Important!!")]),t._v(" "),a("p",[t._v("In next major version, "),a("code",[t._v("warnHtmlInMessage")]),t._v(" option is "),a("code",[t._v("warn")]),t._v(" as default.")])]),t._v(" "),a("h4",{attrs:{id:"sharedmessages"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#sharedmessages"}},[t._v("#")]),t._v(" sharedMessages")]),t._v(" "),a("blockquote",[a("p",[t._v("8.12+")])]),t._v(" "),a("ul",[a("li",[a("p",[a("strong",[t._v("Type:")]),t._v(" "),a("code",[t._v("LocaleMessages")])])]),t._v(" "),a("li",[a("p",[a("strong",[t._v("Default:")]),t._v(" "),a("code",[t._v("undefined")])])])]),t._v(" "),a("p",[t._v("The shared locale messages of localization for components. More detail see "),a("RouterLink",{attrs:{to:"/guide/component.html#shared-locale-messages-for-components"}},[t._v("Component based localization")]),t._v(".")],1),t._v(" "),a("h4",{attrs:{id:"posttranslation"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#posttranslation"}},[t._v("#")]),t._v(" postTranslation")]),t._v(" "),a("blockquote",[a("p",[t._v("8.16+")])]),t._v(" "),a("ul",[a("li",[a("p",[a("strong",[t._v("Type:")]),t._v(" "),a("code",[t._v("PostTranslationHandler")])])]),t._v(" "),a("li",[a("p",[a("strong",[t._v("Default:")]),t._v(" "),a("code",[t._v("null")])])])]),t._v(" "),a("p",[t._v("A handler for post processing of translation. The handler gets after being called with the "),a("code",[t._v("$t")]),t._v(", "),a("code",[t._v("t")]),t._v(", "),a("code",[t._v("$tc")]),t._v(", and "),a("code",[t._v("tc")]),t._v(".")]),t._v(" "),a("p",[t._v("This handler is useful if you want to filter on translated text such as space trimming.")]),t._v(" "),a("h4",{attrs:{id:"componentinstancecreatedlistener"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#componentinstancecreatedlistener"}},[t._v("#")]),t._v(" componentInstanceCreatedListener")]),t._v(" "),a("blockquote",[a("p",[t._v("8.18+")])]),t._v(" "),a("ul",[a("li",[a("p",[a("strong",[t._v("Type:")]),t._v(" "),a("code",[t._v("ComponentInstanceCreatedListener")])])]),t._v(" "),a("li",[a("p",[a("strong",[t._v("Default:")]),t._v(" "),a("code",[t._v("null")])])])]),t._v(" "),a("p",[t._v("A handler for getting notified when component-local instance was created. The handler gets called with new and old (root) VueI18n instances.")]),t._v(" "),a("p",[t._v("This handler is useful when extending the root VueI18n instance and wanting to also apply those extensions to component-local instance.")]),t._v(" "),a("h4",{attrs:{id:"escapeparameterhtml"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#escapeparameterhtml"}},[t._v("#")]),t._v(" escapeParameterHtml")]),t._v(" "),a("blockquote",[a("p",[t._v("8.22+")])]),t._v(" "),a("ul",[a("li",[a("p",[a("strong",[t._v("Type:")]),t._v(" "),a("code",[t._v("Boolean")])])]),t._v(" "),a("li",[a("p",[a("strong",[t._v("Default:")]),t._v(" "),a("code",[t._v("false")])])])]),t._v(" "),a("p",[t._v("If "),a("code",[t._v("escapeParameterHtml")]),t._v(" is configured as true then interpolation parameters are escaped before the message is translated.\nThis is useful when translation output is used in "),a("code",[t._v("v-html")]),t._v(" and the translation resource contains html markup (e.g. "),a("code",[t._v("")]),t._v("\naround a user provided value). This usage pattern mostly occurs when passing precomputed text strings into UI compontents.")]),t._v(" "),a("p",[t._v("The escape process involves replacing the following symbols with their respective HTML character entities: "),a("code",[t._v("<")]),t._v(", "),a("code",[t._v(">")]),t._v(", "),a("code",[t._v('"')]),t._v(", "),a("code",[t._v("'")]),t._v(".")]),t._v(" "),a("p",[t._v("Setting "),a("code",[t._v("escapeParameterHtml")]),t._v(" as true should not break existing functionality but provides a safeguard against a subtle\ntype of XSS attack vectors.")]),t._v(" "),a("h3",{attrs:{id:"properties"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#properties"}},[t._v("#")]),t._v(" Properties")]),t._v(" "),a("h4",{attrs:{id:"locale-2"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#locale-2"}},[t._v("#")]),t._v(" locale")]),t._v(" "),a("ul",[a("li",[a("p",[a("strong",[t._v("Type:")]),t._v(" "),a("code",[t._v("Locale")])])]),t._v(" "),a("li",[a("p",[a("strong",[t._v("Read/Write")])])])]),t._v(" "),a("p",[t._v("The locale of localization. If the locale contains a territory and a dialect, this locale contains an implicit fallback.")]),t._v(" "),a("h4",{attrs:{id:"fallbacklocale-2"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#fallbacklocale-2"}},[t._v("#")]),t._v(" fallbackLocale")]),t._v(" "),a("ul",[a("li",[a("p",[a("strong",[t._v("Type:")]),t._v(" "),a("code",[t._v("FallbackLocale")])])]),t._v(" "),a("li",[a("p",[a("strong",[t._v("Read/Write")])])])]),t._v(" "),a("p",[t._v("The locale of fallback localization. For more complex fallback definitions see "),a("RouterLink",{attrs:{to:"/guide/fallback.html"}},[t._v("fallback")]),t._v(".")],1),t._v(" "),a("h4",{attrs:{id:"messages-2"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#messages-2"}},[t._v("#")]),t._v(" messages")]),t._v(" "),a("ul",[a("li",[a("p",[a("strong",[t._v("Type:")]),t._v(" "),a("code",[t._v("LocaleMessages")])])]),t._v(" "),a("li",[a("p",[a("strong",[t._v("Read only")])])])]),t._v(" "),a("p",[t._v("The locale messages of localization.")]),t._v(" "),a("h4",{attrs:{id:"datetimeformats-2"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#datetimeformats-2"}},[t._v("#")]),t._v(" dateTimeFormats")]),t._v(" "),a("blockquote",[a("p",[t._v("🆕 7.0+")])]),t._v(" "),a("ul",[a("li",[a("p",[a("strong",[t._v("Type:")]),t._v(" "),a("code",[t._v("DateTimeFormats")])])]),t._v(" "),a("li",[a("p",[a("strong",[t._v("Read only")])])])]),t._v(" "),a("p",[t._v("The datetime formats of localization.")]),t._v(" "),a("h4",{attrs:{id:"numberformats-2"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#numberformats-2"}},[t._v("#")]),t._v(" numberFormats")]),t._v(" "),a("blockquote",[a("p",[t._v("🆕 7.0+")])]),t._v(" "),a("ul",[a("li",[a("p",[a("strong",[t._v("Type:")]),t._v(" "),a("code",[t._v("NumberFormats")])])]),t._v(" "),a("li",[a("p",[a("strong",[t._v("Read only")])])])]),t._v(" "),a("p",[t._v("The number formats of localization.")]),t._v(" "),a("h4",{attrs:{id:"availablelocales"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#availablelocales"}},[t._v("#")]),t._v(" availableLocales")]),t._v(" "),a("blockquote",[a("p",[t._v("🆕 8.9.0+")])]),t._v(" "),a("ul",[a("li",[a("p",[a("strong",[t._v("Type:")]),t._v(" "),a("code",[t._v("Locale[]")])])]),t._v(" "),a("li",[a("p",[a("strong",[t._v("Read only")])])])]),t._v(" "),a("p",[t._v("The list of available locales in "),a("code",[t._v("messages")]),t._v(" in lexical order.")]),t._v(" "),a("h4",{attrs:{id:"missing-2"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#missing-2"}},[t._v("#")]),t._v(" missing")]),t._v(" "),a("ul",[a("li",[a("p",[a("strong",[t._v("Type:")]),t._v(" "),a("code",[t._v("MissingHandler")])])]),t._v(" "),a("li",[a("p",[a("strong",[t._v("Read/Write")])])])]),t._v(" "),a("p",[t._v("A handler for localization missing.")]),t._v(" "),a("h4",{attrs:{id:"formatter-2"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#formatter-2"}},[t._v("#")]),t._v(" formatter")]),t._v(" "),a("ul",[a("li",[a("p",[a("strong",[t._v("Type:")]),t._v(" "),a("code",[t._v("Formatter")])])]),t._v(" "),a("li",[a("p",[a("strong",[t._v("Read/Write")])])])]),t._v(" "),a("p",[t._v("The formatter that implemented with "),a("code",[t._v("Formatter")]),t._v(" interface.")]),t._v(" "),a("h4",{attrs:{id:"silenttranslationwarn-2"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#silenttranslationwarn-2"}},[t._v("#")]),t._v(" silentTranslationWarn")]),t._v(" "),a("blockquote",[a("p",[t._v("6.1+, 🆙 8.13")])]),t._v(" "),a("ul",[a("li",[a("p",[a("strong",[t._v("Type:")]),t._v(" "),a("code",[t._v("Boolean | RegExp")])])]),t._v(" "),a("li",[a("p",[a("strong",[t._v("Read/Write")])])])]),t._v(" "),a("p",[t._v("Whether suppress warnings outputted when localization fails.")]),t._v(" "),a("h4",{attrs:{id:"silentfallbackwarn-2"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#silentfallbackwarn-2"}},[t._v("#")]),t._v(" silentFallbackWarn")]),t._v(" "),a("blockquote",[a("p",[t._v("🆕 8.8+, 🆙 8.13")])]),t._v(" "),a("ul",[a("li",[a("p",[a("strong",[t._v("Type:")]),t._v(" "),a("code",[t._v("Boolean | RegExp")])])]),t._v(" "),a("li",[a("p",[a("strong",[t._v("Read/Write")])])])]),t._v(" "),a("p",[t._v("Whether suppress fallback warnings when localization fails.")]),t._v(" "),a("h4",{attrs:{id:"pluralizationrules-2"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#pluralizationrules-2"}},[t._v("#")]),t._v(" pluralizationRules")]),t._v(" "),a("blockquote",[a("p",[t._v("8.5+")])]),t._v(" "),a("ul",[a("li",[a("p",[a("strong",[t._v("Type:")]),t._v(" "),a("code",[t._v("PluralizationRules")])])]),t._v(" "),a("li",[a("p",[a("strong",[t._v("Read/Write")])])])]),t._v(" "),a("p",[t._v("A set of locale-dependent rules for word pluralization.")]),t._v(" "),a("h4",{attrs:{id:"preservedirectivecontent-2"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#preservedirectivecontent-2"}},[t._v("#")]),t._v(" preserveDirectiveContent")]),t._v(" "),a("blockquote",[a("p",[t._v("8.7+")])]),t._v(" "),a("ul",[a("li",[a("p",[a("strong",[t._v("Type:")]),t._v(" "),a("code",[t._v("Boolean")])])]),t._v(" "),a("li",[a("p",[a("strong",[t._v("Read/Write")])])])]),t._v(" "),a("p",[t._v("Whether "),a("code",[t._v("v-t")]),t._v(" directive's element should preserve "),a("code",[t._v("textContent")]),t._v(" after directive is unbinded.")]),t._v(" "),a("h4",{attrs:{id:"warnhtmlinmessage-2"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#warnhtmlinmessage-2"}},[t._v("#")]),t._v(" warnHtmlInMessage")]),t._v(" "),a("blockquote",[a("p",[t._v("8.11+")])]),t._v(" "),a("ul",[a("li",[a("p",[a("strong",[t._v("Type:")]),t._v(" "),a("code",[t._v("WarnHtmlInMessageLevel")])])]),t._v(" "),a("li",[a("p",[a("strong",[t._v("Read/Write")])])])]),t._v(" "),a("p",[t._v("Whether to allow the use locale messages of HTML formatting.")]),t._v(" "),a("p",[t._v("If you set "),a("code",[t._v("warn")]),t._v(" or"),a("code",[t._v("error")]),t._v(", will check the locale messages on the VueI18n instance.")]),t._v(" "),a("p",[t._v("If you are specified "),a("code",[t._v("warn")]),t._v(", a warning will be output at console.")]),t._v(" "),a("p",[t._v("If you are specified "),a("code",[t._v("error")]),t._v(" will occurred an Error.")]),t._v(" "),a("p",[t._v("In VueI18n instance, set the "),a("code",[t._v("off")]),t._v(" as default.")]),t._v(" "),a("h4",{attrs:{id:"posttranslation-2"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#posttranslation-2"}},[t._v("#")]),t._v(" postTranslation")]),t._v(" "),a("blockquote",[a("p",[t._v("8.16+")])]),t._v(" "),a("ul",[a("li",[a("p",[a("strong",[t._v("Type:")]),t._v(" "),a("code",[t._v("PostTranslationHandler")])])]),t._v(" "),a("li",[a("p",[a("strong",[t._v("Read/Write")])])])]),t._v(" "),a("p",[t._v("A handler for post processing of translation.")]),t._v(" "),a("h3",{attrs:{id:"methods"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#methods"}},[t._v("#")]),t._v(" Methods")]),t._v(" "),a("h4",{attrs:{id:"getchoiceindex"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#getchoiceindex"}},[t._v("#")]),t._v(" getChoiceIndex")]),t._v(" "),a("ul",[a("li",[a("p",[a("strong",[t._v("Arguments:")])]),t._v(" "),a("ul",[a("li",[a("code",[t._v("{number} choice")])]),t._v(" "),a("li",[a("code",[t._v("{number} choicesLength")])])])]),t._v(" "),a("li",[a("p",[a("strong",[t._v("Return:")]),t._v(" "),a("code",[t._v("finalChoice {number}")])])])]),t._v(" "),a("p",[t._v("Get pluralization index for current pluralizing number and a given amount of choices.\nCan be overridden through prototype mutation:")]),t._v(" "),a("div",{staticClass:"language-js extra-class"},[a("pre",{pre:!0,attrs:{class:"language-js"}},[a("code",[a("span",{pre:!0,attrs:{class:"token class-name"}},[t._v("VueI18n")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("prototype"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("getChoiceIndex "),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token comment"}},[t._v("/* custom implementation */")]),t._v("\n")])])]),a("p",[t._v("However, for most usages "),a("a",{attrs:{href:"#pluralizationrules"}},[t._v("pluralizationRules constructor option")]),t._v(" should be enough.")]),t._v(" "),a("h4",{attrs:{id:"getlocalemessage-locale"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#getlocalemessage-locale"}},[t._v("#")]),t._v(" getLocaleMessage( locale )")]),t._v(" "),a("ul",[a("li",[a("p",[a("strong",[t._v("Arguments:")])]),t._v(" "),a("ul",[a("li",[a("code",[t._v("{Locale} locale")])])])]),t._v(" "),a("li",[a("p",[a("strong",[t._v("Return:")]),t._v(" "),a("code",[t._v("LocaleMessageObject")])])])]),t._v(" "),a("p",[t._v("Get the locale message of locale.")]),t._v(" "),a("h4",{attrs:{id:"setlocalemessage-locale-message"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#setlocalemessage-locale-message"}},[t._v("#")]),t._v(" setLocaleMessage( locale, message )")]),t._v(" "),a("ul",[a("li",[a("p",[a("strong",[t._v("Arguments:")])]),t._v(" "),a("ul",[a("li",[a("code",[t._v("{Locale} locale")])]),t._v(" "),a("li",[a("code",[t._v("{LocaleMessageObject} message")])])])])]),t._v(" "),a("p",[t._v("Set the locale message of locale.")]),t._v(" "),a("div",{staticClass:"custom-block tip"},[a("p",{staticClass:"custom-block-title"},[t._v("NOTE")]),t._v(" "),a("blockquote",[a("p",[t._v("8.11+")])]),t._v(" "),a("p",[t._v("If you set "),a("code",[t._v("warn")]),t._v(" or"),a("code",[t._v("error")]),t._v(" in the "),a("code",[t._v("warnHtmlInMessage")]),t._v(" property, when this method is executed, it will check if HTML formatting is used for locale message.")])]),t._v(" "),a("h4",{attrs:{id:"mergelocalemessage-locale-message"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#mergelocalemessage-locale-message"}},[t._v("#")]),t._v(" mergeLocaleMessage( locale, message )")]),t._v(" "),a("blockquote",[a("p",[t._v("6.1+")])]),t._v(" "),a("ul",[a("li",[a("p",[a("strong",[t._v("Arguments:")])]),t._v(" "),a("ul",[a("li",[a("code",[t._v("{Locale} locale")])]),t._v(" "),a("li",[a("code",[t._v("{LocaleMessageObject} message")])])])])]),t._v(" "),a("p",[t._v("Merge the registered locale messages with the locale message of locale.")]),t._v(" "),a("div",{staticClass:"custom-block tip"},[a("p",{staticClass:"custom-block-title"},[t._v("NOTE")]),t._v(" "),a("blockquote",[a("p",[t._v("8.11+")])]),t._v(" "),a("p",[t._v("If you set "),a("code",[t._v("warn")]),t._v(" or"),a("code",[t._v("error")]),t._v(" in the "),a("code",[t._v("warnHtmlInMessage")]),t._v(" property, when this method is executed, it will check if HTML formatting is used for locale message.")])]),t._v(" "),a("h4",{attrs:{id:"t-key-locale-values"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#t-key-locale-values"}},[t._v("#")]),t._v(" t( key, [locale], [values] )")]),t._v(" "),a("ul",[a("li",[a("p",[a("strong",[t._v("Arguments:")])]),t._v(" "),a("ul",[a("li",[a("code",[t._v("{Path} key")]),t._v(": required")]),t._v(" "),a("li",[a("code",[t._v("{Locale} locale")]),t._v(": optional")]),t._v(" "),a("li",[a("code",[t._v("{Array | Object} values")]),t._v(": optional")])])]),t._v(" "),a("li",[a("p",[a("strong",[t._v("Return:")]),t._v(" : "),a("code",[t._v("TranslateResult")])])])]),t._v(" "),a("p",[t._v("This is the same as the "),a("code",[t._v("Function")]),t._v(" returned with "),a("code",[t._v("$t")]),t._v(" method. More detail see "),a("a",{attrs:{href:"#t"}},[t._v("$t")]),t._v(".")]),t._v(" "),a("h4",{attrs:{id:"tc-key-choice-values"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#tc-key-choice-values"}},[t._v("#")]),t._v(" tc( key, [choice], [values] )")]),t._v(" "),a("ul",[a("li",[a("p",[a("strong",[t._v("Arguments:")])]),t._v(" "),a("ul",[a("li",[a("code",[t._v("{Path} key")]),t._v(": required")]),t._v(" "),a("li",[a("code",[t._v("{number} choice")]),t._v(": optional, default "),a("code",[t._v("1")])]),t._v(" "),a("li",[a("code",[t._v("{string | Array | Object} values")]),t._v(": optional")])])]),t._v(" "),a("li",[a("p",[a("strong",[t._v("Return:")]),t._v(" "),a("code",[t._v("TranslateResult")])])])]),t._v(" "),a("p",[t._v("This is the same as the "),a("code",[t._v("Function")]),t._v(" returned "),a("code",[t._v("$tc")]),t._v(" method. More detail see "),a("a",{attrs:{href:"#tc"}},[t._v("$tc")]),t._v(".")]),t._v(" "),a("h4",{attrs:{id:"te-key-locale"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#te-key-locale"}},[t._v("#")]),t._v(" te( key, [locale] )")]),t._v(" "),a("ul",[a("li",[a("p",[a("strong",[t._v("Arguments:")])]),t._v(" "),a("ul",[a("li",[a("code",[t._v("{string} key")]),t._v(": required")]),t._v(" "),a("li",[a("code",[t._v("{Locale} locale")]),t._v(": optional")])])]),t._v(" "),a("li",[a("p",[a("strong",[t._v("Return:")]),t._v(" "),a("code",[t._v("boolean")])])])]),t._v(" "),a("p",[t._v("Check whether key path exists in global locale message. If you specified "),a("code",[t._v("locale")]),t._v(", check the locale message of "),a("code",[t._v("locale")]),t._v(".")]),t._v(" "),a("h4",{attrs:{id:"getdatetimeformat-locale"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#getdatetimeformat-locale"}},[t._v("#")]),t._v(" getDateTimeFormat ( locale )")]),t._v(" "),a("blockquote",[a("p",[t._v("🆕 7.0+")])]),t._v(" "),a("ul",[a("li",[a("p",[a("strong",[t._v("Arguments:")])]),t._v(" "),a("ul",[a("li",[a("code",[t._v("{Locale} locale")])])])]),t._v(" "),a("li",[a("p",[a("strong",[t._v("Return:")]),t._v(" "),a("code",[t._v("DateTimeFormat")])])])]),t._v(" "),a("p",[t._v("Get the datetime format of locale.")]),t._v(" "),a("h4",{attrs:{id:"setdatetimeformat-locale-format"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#setdatetimeformat-locale-format"}},[t._v("#")]),t._v(" setDateTimeFormat ( locale, format )")]),t._v(" "),a("blockquote",[a("p",[t._v("🆕 7.0+")])]),t._v(" "),a("ul",[a("li",[a("p",[a("strong",[t._v("Arguments:")])]),t._v(" "),a("ul",[a("li",[a("code",[t._v("{Locale} locale")])]),t._v(" "),a("li",[a("code",[t._v("{DateTimeFormat} format")])])])])]),t._v(" "),a("p",[t._v("Set the datetime format of locale.")]),t._v(" "),a("h4",{attrs:{id:"mergedatetimeformat-locale-format"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#mergedatetimeformat-locale-format"}},[t._v("#")]),t._v(" mergeDateTimeFormat ( locale, format )")]),t._v(" "),a("blockquote",[a("p",[t._v("🆕 7.0+")])]),t._v(" "),a("ul",[a("li",[a("p",[a("strong",[t._v("Arguments:")])]),t._v(" "),a("ul",[a("li",[a("code",[t._v("{Locale} locale")])]),t._v(" "),a("li",[a("code",[t._v("{DateTimeFormat} format")])])])])]),t._v(" "),a("p",[t._v("Merge the registered datetime formats with the datetime format of locale.")]),t._v(" "),a("h4",{attrs:{id:"d-value-key-locale"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#d-value-key-locale"}},[t._v("#")]),t._v(" d( value, [key], [locale] )")]),t._v(" "),a("blockquote",[a("p",[t._v("🆕 7.0+")])]),t._v(" "),a("ul",[a("li",[a("p",[a("strong",[t._v("Arguments:")])]),t._v(" "),a("ul",[a("li",[a("code",[t._v("{number | Date} value")]),t._v(": required")]),t._v(" "),a("li",[a("code",[t._v("{Path | Object} key")]),t._v(": optional")]),t._v(" "),a("li",[a("code",[t._v("{Locale | Object} locale")]),t._v(": optional")])])]),t._v(" "),a("li",[a("p",[a("strong",[t._v("Return:")]),t._v(" "),a("code",[t._v("DateTimeFormatResult")])])])]),t._v(" "),a("p",[t._v("This is the same as "),a("code",[t._v("$d")]),t._v(" method of Vue instance method. More detail see "),a("a",{attrs:{href:"#d"}},[t._v("$d")]),t._v(".")]),t._v(" "),a("h4",{attrs:{id:"getnumberformat-locale"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#getnumberformat-locale"}},[t._v("#")]),t._v(" getNumberFormat ( locale )")]),t._v(" "),a("blockquote",[a("p",[t._v("🆕 7.0+")])]),t._v(" "),a("ul",[a("li",[a("p",[a("strong",[t._v("Arguments:")])]),t._v(" "),a("ul",[a("li",[a("code",[t._v("{Locale} locale")])])])]),t._v(" "),a("li",[a("p",[a("strong",[t._v("Return:")]),t._v(" "),a("code",[t._v("NumberFormat")])])])]),t._v(" "),a("p",[t._v("Get the number format of locale.")]),t._v(" "),a("h4",{attrs:{id:"setnumberformat-locale-format"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#setnumberformat-locale-format"}},[t._v("#")]),t._v(" setNumberFormat ( locale, format )")]),t._v(" "),a("blockquote",[a("p",[t._v("🆕 7.0+")])]),t._v(" "),a("ul",[a("li",[a("p",[a("strong",[t._v("Arguments:")])]),t._v(" "),a("ul",[a("li",[a("code",[t._v("{Locale} locale")])]),t._v(" "),a("li",[a("code",[t._v("{NumberFormat} format")])])])])]),t._v(" "),a("p",[t._v("Set the number format of locale.")]),t._v(" "),a("h4",{attrs:{id:"mergenumberformat-locale-format"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#mergenumberformat-locale-format"}},[t._v("#")]),t._v(" mergeNumberFormat ( locale, format )")]),t._v(" "),a("blockquote",[a("p",[t._v("🆕 7.0+")])]),t._v(" "),a("ul",[a("li",[a("p",[a("strong",[t._v("Arguments:")])]),t._v(" "),a("ul",[a("li",[a("code",[t._v("{Locale} locale")])]),t._v(" "),a("li",[a("code",[t._v("{NumberFormat} format")])])])])]),t._v(" "),a("p",[t._v("Merge the registered number formats with the number format of locale.")]),t._v(" "),a("h4",{attrs:{id:"n-value-format-locale"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#n-value-format-locale"}},[t._v("#")]),t._v(" n( value, [format], [locale] )")]),t._v(" "),a("blockquote",[a("p",[t._v("🆕 7.0+")])]),t._v(" "),a("ul",[a("li",[a("p",[a("strong",[t._v("Arguments:")])]),t._v(" "),a("ul",[a("li",[a("code",[t._v("{number} value")]),t._v(": required")]),t._v(" "),a("li",[a("code",[t._v("{Path | Object} format")]),t._v(": optional")]),t._v(" "),a("li",[a("code",[t._v("{Locale} locale")]),t._v(": optional")])])]),t._v(" "),a("li",[a("p",[a("strong",[t._v("Return:")]),t._v(" "),a("code",[t._v("NumberFormatResult")])])])]),t._v(" "),a("p",[t._v("This is the same as "),a("code",[t._v("$n")]),t._v(" method of Vue instance method. More detail see "),a("a",{attrs:{href:"#n"}},[t._v("$n")]),t._v(".")]),t._v(" "),a("h2",{attrs:{id:"directives"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#directives"}},[t._v("#")]),t._v(" Directives")]),t._v(" "),a("blockquote",[a("p",[t._v("🆕 7.3+")])]),t._v(" "),a("h3",{attrs:{id:"v-t"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#v-t"}},[t._v("#")]),t._v(" v-t")]),t._v(" "),a("ul",[a("li",[a("p",[a("strong",[t._v("Expects:")]),t._v(" "),a("code",[t._v("string | Object")])])]),t._v(" "),a("li",[a("p",[a("strong",[t._v("Modifiers:")])]),t._v(" "),a("ul",[a("li",[a("code",[t._v(".preserve")]),t._v(": (8.7.0+) preserves element "),a("code",[t._v("textContent")]),t._v(" when directive is unbinded.")])])]),t._v(" "),a("li",[a("p",[a("strong",[t._v("Details:")])])])]),t._v(" "),a("p",[t._v("Update the element "),a("code",[t._v("textContent")]),t._v(" that localized with locale messages. You can use string syntax or object syntax. string syntax can be specified as a keypath of locale messages. If you can be used object syntax, you need to specify as the object key the following params:")]),t._v(" "),a("ul",[a("li",[a("code",[t._v("path")]),t._v(": required, key of locale messages")]),t._v(" "),a("li",[a("code",[t._v("locale")]),t._v(": optional, locale")]),t._v(" "),a("li",[a("code",[t._v("args")]),t._v(": optional, for list or named formatting")])]),t._v(" "),a("div",{staticClass:"custom-block tip"},[a("p",{staticClass:"custom-block-title"},[t._v("NOTE")]),t._v(" "),a("p",[t._v("The element "),a("code",[t._v("textContent")]),t._v(" will be cleared by default when "),a("code",[t._v("v-t")]),t._v(" directive is unbinded. This might be undesirable situation when used inside "),a("a",{attrs:{href:"https://vuejs.org/v2/guide/transitions.html",target:"_blank",rel:"noopener noreferrer"}},[t._v("transitions"),a("OutboundLink")],1),t._v(". To preserve "),a("code",[t._v("textContent")]),t._v(" data after directive unbind use "),a("code",[t._v(".preserve")]),t._v(" modifier or global "),a("a",{attrs:{href:"#preservedirectivecontent"}},[a("code",[t._v("preserveDirectiveContent")]),t._v(" option")]),t._v(".")])]),t._v(" "),a("ul",[a("li",[a("strong",[t._v("Examples:")])])]),t._v(" "),a("div",{staticClass:"language-html extra-class"},[a("pre",{pre:!0,attrs:{class:"language-html"}},[a("code",[a("span",{pre:!0,attrs:{class:"token comment"}},[t._v("\x3c!-- string syntax: literal --\x3e")]),t._v("\n"),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("p")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v("v-t")]),a("span",{pre:!0,attrs:{class:"token attr-value"}},[a("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("'")]),t._v("foo.bar"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("'")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n\n"),a("span",{pre:!0,attrs:{class:"token comment"}},[t._v("\x3c!-- string syntax: binding via data or computed props --\x3e")]),t._v("\n"),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("p")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v("v-t")]),a("span",{pre:!0,attrs:{class:"token attr-value"}},[a("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),t._v("msg"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n\n"),a("span",{pre:!0,attrs:{class:"token comment"}},[t._v("\x3c!-- object syntax: literal --\x3e")]),t._v("\n"),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("p")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v("v-t")]),a("span",{pre:!0,attrs:{class:"token attr-value"}},[a("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),t._v("{ path: "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("'")]),t._v("hi"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("'")]),t._v(", locale: "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("'")]),t._v("ja"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("'")]),t._v(", args: { name: "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("'")]),t._v("kazupon"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("'")]),t._v(" } }"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n\n"),a("span",{pre:!0,attrs:{class:"token comment"}},[t._v("\x3c!-- object syntax: binding via data or computed props --\x3e")]),t._v("\n"),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("p")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v("v-t")]),a("span",{pre:!0,attrs:{class:"token attr-value"}},[a("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),t._v("{ path: greeting, args: { name: fullName } }"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n\n"),a("span",{pre:!0,attrs:{class:"token comment"}},[t._v("\x3c!-- with preserve modifier --\x3e")]),t._v("\n"),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("p")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v("v-t.preserve")]),a("span",{pre:!0,attrs:{class:"token attr-value"}},[a("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("'")]),t._v("foo.bar"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("'")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n")])])]),a("ul",[a("li",[a("strong",[t._v("See also:")]),t._v(" "),a("RouterLink",{attrs:{to:"/guide/directive.html"}},[t._v("Custom directive localization")])],1)]),t._v(" "),a("h2",{attrs:{id:"components"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#components"}},[t._v("#")]),t._v(" Components")]),t._v(" "),a("h3",{attrs:{id:"i18n-functional-component"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#i18n-functional-component"}},[t._v("#")]),t._v(" i18n functional component")]),t._v(" "),a("blockquote",[a("p",[t._v("🆕 7.0+")])]),t._v(" "),a("h4",{attrs:{id:"props"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#props"}},[t._v("#")]),t._v(" Props:")]),t._v(" "),a("ul",[a("li",[a("code",[t._v("path {Path}")]),t._v(": required, keypath of locale messages")]),t._v(" "),a("li",[a("code",[t._v("locale {Locale}")]),t._v(": optional, locale")]),t._v(" "),a("li",[a("code",[t._v("tag {string | boolean | Object}")]),t._v(": optional, default "),a("code",[t._v("'span'")])]),t._v(" "),a("li",[a("code",[t._v("places {Array | Object}")]),t._v(": optional (7.2+)")])]),t._v(" "),a("div",{staticClass:"custom-block danger"},[a("p",{staticClass:"custom-block-title"},[t._v("Important!!")]),t._v(" "),a("p",[t._v("In next major version, "),a("code",[t._v("places")]),t._v(" prop is deprecated. Please switch to slots syntax.")])]),t._v(" "),a("h4",{attrs:{id:"usage"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#usage"}},[t._v("#")]),t._v(" Usage:")]),t._v(" "),a("div",{staticClass:"language-html extra-class"},[a("pre",{pre:!0,attrs:{class:"language-html"}},[a("code",[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("div")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v("id")]),a("span",{pre:!0,attrs:{class:"token attr-value"}},[a("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),t._v("app"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token comment"}},[t._v("\x3c!-- ... --\x3e")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("i18n")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v("path")]),a("span",{pre:!0,attrs:{class:"token attr-value"}},[a("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),t._v("term"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])]),t._v(" "),a("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v("tag")]),a("span",{pre:!0,attrs:{class:"token attr-value"}},[a("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),t._v("label"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])]),t._v(" "),a("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v("for")]),a("span",{pre:!0,attrs:{class:"token attr-value"}},[a("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),t._v("tos"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("a")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v(":href")]),a("span",{pre:!0,attrs:{class:"token attr-value"}},[a("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),t._v("url"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])]),t._v(" "),a("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v("target")]),a("span",{pre:!0,attrs:{class:"token attr-value"}},[a("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),t._v("_blank"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("{{ $t('tos') }}"),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token comment"}},[t._v("\x3c!-- ... --\x3e")]),t._v("\n"),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n")])])]),a("div",{staticClass:"language-js extra-class"},[a("pre",{pre:!0,attrs:{class:"language-js"}},[a("code",[a("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("const")]),t._v(" messages "),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("en")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("tos")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v("'Term of Service'")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("term")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v("'I accept xxx {0}.'")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("ja")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("tos")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v("'利用規約'")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("term")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v("'私は xxx の{0}に同意します。'")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n\n"),a("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("const")]),t._v(" i18n "),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("new")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token class-name"}},[t._v("VueI18n")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("locale")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v("'en'")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n messages\n"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v("\n"),a("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("new")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token class-name"}},[t._v("Vue")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n i18n"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("data")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("url")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v("'/term'")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),a("span",{pre:!0,attrs:{class:"token function"}},[t._v("$mount")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),a("span",{pre:!0,attrs:{class:"token string"}},[t._v("'#app'")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v("\n")])])]),a("h4",{attrs:{id:"see-also"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#see-also"}},[t._v("#")]),t._v(" See also:")]),t._v(" "),a("p",[a("RouterLink",{attrs:{to:"/guide/interpolation.html"}},[t._v("Component interpolation")])],1),t._v(" "),a("h3",{attrs:{id:"i18n-n-functional-component"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#i18n-n-functional-component"}},[t._v("#")]),t._v(" i18n-n functional component")]),t._v(" "),a("blockquote",[a("p",[t._v("🆕 8.10+")])]),t._v(" "),a("h4",{attrs:{id:"props-2"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#props-2"}},[t._v("#")]),t._v(" Props:")]),t._v(" "),a("ul",[a("li",[a("code",[t._v("value {number}")]),t._v(": required, number to format")]),t._v(" "),a("li",[a("code",[t._v("format {string | NumberFormatOptions}")]),t._v(": optional, number format name or object with explicit format options")]),t._v(" "),a("li",[a("code",[t._v("locale {Locale}")]),t._v(": optional, locale")]),t._v(" "),a("li",[a("code",[t._v("tag {string | boolean | Object}")]),t._v(": optional, default "),a("code",[t._v("'span'")])])]),t._v(" "),a("h4",{attrs:{id:"usage-2"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#usage-2"}},[t._v("#")]),t._v(" Usage:")]),t._v(" "),a("div",{staticClass:"language-html extra-class"},[a("pre",{pre:!0,attrs:{class:"language-html"}},[a("code",[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("div")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v("id")]),a("span",{pre:!0,attrs:{class:"token attr-value"}},[a("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),t._v("app"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token comment"}},[t._v("\x3c!-- ... --\x3e")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("i18n-n")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v(":value")]),a("span",{pre:!0,attrs:{class:"token attr-value"}},[a("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),t._v("money"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])]),t._v(" "),a("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v("format")]),a("span",{pre:!0,attrs:{class:"token attr-value"}},[a("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),t._v("currency"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])]),t._v(" "),a("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v("tag")]),a("span",{pre:!0,attrs:{class:"token attr-value"}},[a("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),t._v("label"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("span")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token attr-name"}},[a("span",{pre:!0,attrs:{class:"token namespace"}},[t._v("v-slot:")]),t._v("currency")]),a("span",{pre:!0,attrs:{class:"token attr-value"}},[a("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),t._v("slotProps"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])]),t._v(" "),a("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v("class")]),a("span",{pre:!0,attrs:{class:"token attr-value"}},[a("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),t._v("font-weight: bold"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("{{ slotProps.currency }}"),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("span")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token comment"}},[t._v("\x3c!-- ... --\x3e")]),t._v("\n"),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n")])])]),a("div",{staticClass:"language-js extra-class"},[a("pre",{pre:!0,attrs:{class:"language-js"}},[a("code",[a("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("var")]),t._v(" numberFormats "),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token string-property property"}},[t._v("'en-US'")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("currency")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("style")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v("'currency'")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("currency")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v("'USD'")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token string-property property"}},[t._v("'ja-JP'")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("currency")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("style")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v("'currency'")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("currency")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v("'JPY'")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n\n"),a("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("const")]),t._v(" i18n "),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("new")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token class-name"}},[t._v("VueI18n")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("locale")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v("'en-US'")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n numberFormats\n"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v("\n"),a("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("new")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token class-name"}},[t._v("Vue")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n i18n"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("data")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("money")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token number"}},[t._v("10234")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),a("span",{pre:!0,attrs:{class:"token function"}},[t._v("$mount")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),a("span",{pre:!0,attrs:{class:"token string"}},[t._v("'#app'")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v("\n")])])]),a("h4",{attrs:{id:"scoped-slots"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#scoped-slots"}},[t._v("#")]),t._v(" Scoped slots")]),t._v(" "),a("p",[a("code",[t._v("")]),t._v(" functional component can accept a number of named scoped slots. List of supported slot names is based on "),a("a",{attrs:{href:"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NumberFormat/formatToParts",target:"_blank",rel:"noopener noreferrer"}},[a("code",[t._v("Intl.NumberFormat.formatToParts()")]),t._v(" output types"),a("OutboundLink")],1),t._v(":")]),t._v(" "),a("ul",[a("li",[a("code",[t._v("currency")])]),t._v(" "),a("li",[a("code",[t._v("decimal")])]),t._v(" "),a("li",[a("code",[t._v("fraction")])]),t._v(" "),a("li",[a("code",[t._v("group")])]),t._v(" "),a("li",[a("code",[t._v("infinity")])]),t._v(" "),a("li",[a("code",[t._v("integer")])]),t._v(" "),a("li",[a("code",[t._v("literal")])]),t._v(" "),a("li",[a("code",[t._v("minusSign")])]),t._v(" "),a("li",[a("code",[t._v("nan")])]),t._v(" "),a("li",[a("code",[t._v("plusSign")])]),t._v(" "),a("li",[a("code",[t._v("percentSign")])])]),t._v(" "),a("p",[t._v("Each of these named scoped slots will accept three scope parameters:")]),t._v(" "),a("ul",[a("li",[a("code",[t._v("[slotName] {FormattedNumberPartType}")]),t._v(": parameter of the same name as actual slot name (like "),a("code",[t._v("integer")]),t._v(")")]),t._v(" "),a("li",[a("code",[t._v("index {Number}")]),t._v(": index of the specific part in the array of number parts")]),t._v(" "),a("li",[a("code",[t._v("parts {Array}")]),t._v(": array of all formatted number parts")])]),t._v(" "),a("h4",{attrs:{id:"see-also-2"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#see-also-2"}},[t._v("#")]),t._v(" See also:")]),t._v(" "),a("p",[a("RouterLink",{attrs:{to:"/guide/number.html#custom-formatting"}},[t._v("Number custom formatting")])],1),t._v(" "),a("h2",{attrs:{id:"special-attributes"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#special-attributes"}},[t._v("#")]),t._v(" Special Attributes")]),t._v(" "),a("h3",{attrs:{id:"place"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#place"}},[t._v("#")]),t._v(" place")]),t._v(" "),a("blockquote",[a("p",[t._v("🆕 7.2+")])]),t._v(" "),a("h4",{attrs:{id:"expects-number-string"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#expects-number-string"}},[t._v("#")]),t._v(" Expects: "),a("code",[t._v("{number | string}")])]),t._v(" "),a("p",[t._v("Used on component interpolation to indicate which index of list formatting or key of named formatting.")]),t._v(" "),a("p",[t._v("For detailed usage, see the guide section linked below.")]),t._v(" "),a("h4",{attrs:{id:"see-also-3"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#see-also-3"}},[t._v("#")]),t._v(" See also:")]),t._v(" "),a("p",[a("RouterLink",{attrs:{to:"/guide/interpolation.html"}},[t._v("Component interpolation")])],1)])}),[],!1,null,null,null);e.default=o.exports}}]); \ No newline at end of file diff --git a/assets/js/11.208ba717.js b/assets/js/11.208ba717.js new file mode 100644 index 000000000..41b8b4eda --- /dev/null +++ b/assets/js/11.208ba717.js @@ -0,0 +1 @@ +(window.webpackJsonp=window.webpackJsonp||[]).push([[11],{459:function(t,s,a){"use strict";a.r(s);var n=a(44),e=Object(n.a)({},(function(){var t=this,s=t.$createElement,a=t._self._c||s;return a("ContentSlotsDistributor",{attrs:{"slot-key":t.$parent.slotKey}},[a("h1",{attrs:{id:"component-based-localization"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#component-based-localization"}},[t._v("#")]),t._v(" Component based localization")]),t._v(" "),a("p",[t._v("In general, locale info (e.g. "),a("code",[t._v("locale")]),t._v(","),a("code",[t._v("messages")]),t._v(", etc) is set as constructor option of "),a("code",[t._v("VueI18n")]),t._v(" instance and it sets "),a("code",[t._v("i18n")]),t._v(" option as root Vue instance.")]),t._v(" "),a("p",[t._v("Therefore you can globally translate using "),a("code",[t._v("$t")]),t._v(" or "),a("code",[t._v("$tc")]),t._v(" in the root Vue instance and any composed component. You can also manage locale info for each component separately, which might be more convenient due to Vue components oriented design.")]),t._v(" "),a("p",[t._v("Component based localization example:")]),t._v(" "),a("div",{staticClass:"language-js extra-class"},[a("pre",{pre:!0,attrs:{class:"language-js"}},[a("code",[a("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// setup locale info for root Vue instance")]),t._v("\n"),a("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("const")]),t._v(" i18n "),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("new")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token class-name"}},[t._v("VueI18n")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("locale")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v("'ja'")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("messages")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("en")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("message")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("hello")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v("'hello world'")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("greeting")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v("'good morning'")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("ja")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("message")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("hello")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v("'こんにちは、世界'")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("greeting")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v("'おはようございます'")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v("\n\n"),a("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// Define component")]),t._v("\n"),a("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("const")]),t._v(" Component1 "),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("template")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token template-string"}},[a("span",{pre:!0,attrs:{class:"token template-punctuation string"}},[t._v("`")]),a("span",{pre:!0,attrs:{class:"token string"}},[t._v('\n
\n

Component1 locale messages: {{ $t("message.hello") }}

\n

Fallback global locale messages: {{ $t("message.greeting") }}

\n
')]),a("span",{pre:!0,attrs:{class:"token template-punctuation string"}},[t._v("`")])]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("i18n")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// `i18n` option, setup locale info for component")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("messages")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("en")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("message")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("hello")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v("'hello component1'")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("ja")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("message")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("hello")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v("'こんにちは、component1'")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n\n"),a("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("new")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token class-name"}},[t._v("Vue")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n i18n"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("components")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n Component1\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),a("span",{pre:!0,attrs:{class:"token function"}},[t._v("$mount")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),a("span",{pre:!0,attrs:{class:"token string"}},[t._v("'#app'")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v("\n")])])]),a("p",[t._v("Template:")]),t._v(" "),a("div",{staticClass:"language-html extra-class"},[a("pre",{pre:!0,attrs:{class:"language-html"}},[a("code",[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("div")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v("id")]),a("span",{pre:!0,attrs:{class:"token attr-value"}},[a("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),t._v("app"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("p")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v('{{ $t("message.hello") }}'),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("component1")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n"),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n")])])]),a("p",[t._v("Outputs the following:")]),t._v(" "),a("div",{staticClass:"language-html extra-class"},[a("pre",{pre:!0,attrs:{class:"language-html"}},[a("code",[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("div")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v("id")]),a("span",{pre:!0,attrs:{class:"token attr-value"}},[a("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),t._v("app"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("p")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("こんにちは、世界"),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("div")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v("class")]),a("span",{pre:!0,attrs:{class:"token attr-value"}},[a("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),t._v("container"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("p")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("Component1 locale messages: こんにちは、component1"),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("p")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("Fallback global locale messages: おはようございます"),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n"),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n")])])]),a("p",[t._v("As in the example above, if the component doesn't have the locale message, it falls back to globally defined localization info. The component uses the language set in the root instance (in the above example: "),a("code",[t._v("locale: 'ja'")]),t._v(").")]),t._v(" "),a("p",[t._v("Note that, by default, falling back to root locale generates two warnings in the console:")]),t._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[t._v("[vue-i18n] Value of key 'message.greeting' is not a string!\n[vue-i18n] Fall back to translate the keypath 'message.greeting' with root locale.\n")])])]),a("p",[t._v("To suppress these warnings (while keeping those which warn of the total absence of translation for the given key) set "),a("code",[t._v("silentFallbackWarn: true")]),t._v(" when initializing the "),a("code",[t._v("VueI18n")]),t._v(" instance.")]),t._v(" "),a("p",[t._v("If you want to localize using the component locale, you can do that with "),a("code",[t._v("sync: false")]),t._v(" and "),a("code",[t._v("locale")]),t._v(" in the "),a("code",[t._v("i18n")]),t._v(" option.")]),t._v(" "),a("h2",{attrs:{id:"shared-locale-messages-for-components"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#shared-locale-messages-for-components"}},[t._v("#")]),t._v(" Shared locale messages for components")]),t._v(" "),a("p",[t._v("Sometimes you may want to import shared locale messages for certain components, not fallback from global locale messages (e.g. common messages of certain feature for components.")]),t._v(" "),a("p",[t._v("You can use "),a("code",[t._v("sharedMessages")]),t._v(" options of "),a("code",[t._v("i18n")]),t._v(".")]),t._v(" "),a("p",[t._v("Common Locale Messages example:")]),t._v(" "),a("div",{staticClass:"language-js extra-class"},[a("pre",{pre:!0,attrs:{class:"language-js"}},[a("code",[a("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("export")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("default")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("en")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("buttons")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("save")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v('"Save"')]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// ...")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("ja")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("buttons")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("save")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v('"保存"')]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// ...")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n")])])]),a("p",[t._v("Components:")]),t._v(" "),a("div",{staticClass:"language-js extra-class"},[a("pre",{pre:!0,attrs:{class:"language-js"}},[a("code",[a("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("import")]),t._v(" commonMessage "),a("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("from")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v("'./locales/common'")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// import common locale messages")]),t._v("\n\n"),a("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("export")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("default")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("name")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v("'ServiceModal'")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("template")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token template-string"}},[a("span",{pre:!0,attrs:{class:"token template-punctuation string"}},[t._v("`")]),a("span",{pre:!0,attrs:{class:"token string"}},[t._v('\n \n ')]),a("span",{pre:!0,attrs:{class:"token template-punctuation string"}},[t._v("`")])]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("i18n")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("messages")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v("...")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("sharedMessages")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" commonMessages\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n")])])]),a("p",[t._v("If "),a("code",[t._v("sharedMessages")]),t._v(" option is specified along with the "),a("code",[t._v("messages")]),t._v(" option, those messages will be merged into locale messages into the VueI18n instance of the target component.")]),t._v(" "),a("h2",{attrs:{id:"translation-in-functional-component"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#translation-in-functional-component"}},[t._v("#")]),t._v(" Translation in functional component")]),t._v(" "),a("p",[t._v("When using a functional component, all data (including "),a("code",[t._v("props")]),t._v(", "),a("code",[t._v("children")]),t._v(", "),a("code",[t._v("slots")]),t._v(", "),a("code",[t._v("parent")]),t._v(", etc.) is passed through the "),a("code",[t._v("context")]),t._v(" containing the attributes, and it doesn't recognize the "),a("code",[t._v("this")]),t._v(" scope, so when using the vue-i18n on functional components, you must refer to "),a("code",[t._v("$t")]),t._v(" as "),a("code",[t._v("parent.$t")]),t._v(", check the example below:")]),t._v(" "),a("div",{staticClass:"language-html extra-class"},[a("pre",{pre:!0,attrs:{class:"language-html"}},[a("code",[t._v("...\n"),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("div")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("a")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v("href")]),a("span",{pre:!0,attrs:{class:"token attr-value"}},[a("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),t._v("#"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])]),t._v(" "),a("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v("target")]),a("span",{pre:!0,attrs:{class:"token attr-value"}},[a("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),t._v("_blank"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])]),t._v(" "),a("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v("rel")]),a("span",{pre:!0,attrs:{class:"token attr-value"}},[a("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),t._v("noopener noreferrer"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("img")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v("src")]),a("span",{pre:!0,attrs:{class:"token attr-value"}},[a("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),t._v("./assets/example.jpg"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])]),t._v(" "),a("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v(":alt")]),a("span",{pre:!0,attrs:{class:"token attr-value"}},[a("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),t._v("parent.$t("),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("'")]),t._v("message.hello"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("'")]),t._v(")"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n"),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n...\n")])])])])}),[],!1,null,null,null);s.default=e.exports}}]); \ No newline at end of file diff --git a/assets/js/12.5820d0d0.js b/assets/js/12.5820d0d0.js new file mode 100644 index 000000000..dd451b96a --- /dev/null +++ b/assets/js/12.5820d0d0.js @@ -0,0 +1 @@ +(window.webpackJsonp=window.webpackJsonp||[]).push([[12],{461:function(t,s,a){"use strict";a.r(s);var n=a(44),r=Object(n.a)({},(function(){var t=this,s=t.$createElement,a=t._self._c||s;return a("ContentSlotsDistributor",{attrs:{"slot-key":t.$parent.slotKey}},[a("h1",{attrs:{id:"datetime-localization"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#datetime-localization"}},[t._v("#")]),t._v(" DateTime localization")]),t._v(" "),a("div",{staticClass:"custom-block tip"},[a("p",{staticClass:"custom-block-title"},[t._v("Support Version")]),t._v(" "),a("p",[t._v("🆕 7.0+")])]),t._v(" "),a("p",[t._v("You can localize the datetime with your definition formats.")]),t._v(" "),a("p",[t._v("DateTime formats the below:")]),t._v(" "),a("div",{staticClass:"language-js extra-class"},[a("pre",{pre:!0,attrs:{class:"language-js"}},[a("code",[a("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("const")]),t._v(" dateTimeFormats "),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token string-property property"}},[t._v("'en-US'")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("short")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("year")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v("'numeric'")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("month")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v("'short'")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("day")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v("'numeric'")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("long")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("year")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v("'numeric'")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("month")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v("'long'")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("day")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v("'numeric'")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("weekday")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v("'long'")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("hour")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v("'numeric'")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("minute")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v("'numeric'")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token string-property property"}},[t._v("'ja-JP'")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("short")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("year")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v("'numeric'")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("month")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v("'short'")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("day")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v("'numeric'")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("long")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("year")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v("'numeric'")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("month")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v("'long'")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("day")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v("'numeric'")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("weekday")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v("'long'")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("hour")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v("'numeric'")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("minute")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v("'numeric'")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("hour12")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token boolean"}},[t._v("true")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n")])])]),a("p",[t._v("As seen above, you can define named datetime format (e.g. "),a("code",[t._v("short")]),t._v(", "),a("code",[t._v("long")]),t._v(", etc), and you need to use "),a("a",{attrs:{href:"http://www.ecma-international.org/ecma-402/2.0/#sec-intl-datetimeformat-constructor",target:"_blank",rel:"noopener noreferrer"}},[t._v("the options with ECMA-402 Intl.DateTimeFormat"),a("OutboundLink")],1)]),t._v(" "),a("p",[t._v("After that, when using the locale messages, you need to specify the "),a("code",[t._v("dateTimeFormats")]),t._v(" option of the "),a("code",[t._v("VueI18n")]),t._v(" constructor:")]),t._v(" "),a("div",{staticClass:"language-js extra-class"},[a("pre",{pre:!0,attrs:{class:"language-js"}},[a("code",[a("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("const")]),t._v(" i18n "),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("new")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token class-name"}},[t._v("VueI18n")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n dateTimeFormats\n"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v("\n\n"),a("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("new")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token class-name"}},[t._v("Vue")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n i18n\n"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),a("span",{pre:!0,attrs:{class:"token function"}},[t._v("$mount")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),a("span",{pre:!0,attrs:{class:"token string"}},[t._v("'#app'")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v("\n")])])]),a("p",[t._v("Template the below:")]),t._v(" "),a("div",{staticClass:"language-html extra-class"},[a("pre",{pre:!0,attrs:{class:"language-html"}},[a("code",[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("div")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v("id")]),a("span",{pre:!0,attrs:{class:"token attr-value"}},[a("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),t._v("app"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("p")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("{{ $d(new Date(), 'short') }}"),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("p")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("{{ $d(new Date(), 'long', 'ja-JP') }}"),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n"),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n")])])]),a("p",[t._v("Output the below:")]),t._v(" "),a("div",{staticClass:"language-html extra-class"},[a("pre",{pre:!0,attrs:{class:"language-html"}},[a("code",[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("div")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v("id")]),a("span",{pre:!0,attrs:{class:"token attr-value"}},[a("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),t._v("app"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("p")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("Jan 18, 2021"),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("p")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("2021年1月18日日曜日 午前5:47"),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n"),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n")])])])])}),[],!1,null,null,null);s.default=r.exports}}]); \ No newline at end of file diff --git a/assets/js/13.3075be29.js b/assets/js/13.3075be29.js new file mode 100644 index 000000000..53d5620f4 --- /dev/null +++ b/assets/js/13.3075be29.js @@ -0,0 +1 @@ +(window.webpackJsonp=window.webpackJsonp||[]).push([[13],{464:function(t,s,a){"use strict";a.r(s);var n=a(44),e=Object(n.a)({},(function(){var t=this,s=t.$createElement,a=t._self._c||s;return a("ContentSlotsDistributor",{attrs:{"slot-key":t.$parent.slotKey}},[a("h1",{attrs:{id:"custom-directive-localization"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#custom-directive-localization"}},[t._v("#")]),t._v(" Custom directive localization")]),t._v(" "),a("div",{staticClass:"custom-block tip"},[a("p",{staticClass:"custom-block-title"},[t._v("Support Version")]),t._v(" "),a("p",[t._v("🆕 7.3+")])]),t._v(" "),a("p",[t._v("You can translate not only with "),a("code",[t._v("v-t")]),t._v(" custom directive, but also with the "),a("code",[t._v("$t")]),t._v("\nmethod.")]),t._v(" "),a("h2",{attrs:{id:"string-syntax"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#string-syntax"}},[t._v("#")]),t._v(" String syntax")]),t._v(" "),a("p",[t._v("You can pass the keypath of locale messages with string syntax.")]),t._v(" "),a("p",[t._v("Javascript:")]),t._v(" "),a("div",{staticClass:"language-js extra-class"},[a("pre",{pre:!0,attrs:{class:"language-js"}},[a("code",[a("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("new")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token class-name"}},[t._v("Vue")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("i18n")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("new")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token class-name"}},[t._v("VueI18n")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("locale")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v("'en'")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("messages")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("en")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("hello")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v("'hi there!'")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("ja")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("hello")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v("'こんにちは!'")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("data")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("path")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v("'hello'")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),a("span",{pre:!0,attrs:{class:"token function"}},[t._v("$mount")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),a("span",{pre:!0,attrs:{class:"token string"}},[t._v("'#string-syntax'")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v("\n")])])]),a("p",[t._v("Templates:")]),t._v(" "),a("div",{staticClass:"language-html extra-class"},[a("pre",{pre:!0,attrs:{class:"language-html"}},[a("code",[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("div")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v("id")]),a("span",{pre:!0,attrs:{class:"token attr-value"}},[a("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),t._v("string-syntax"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token comment"}},[t._v("\x3c!-- string literal --\x3e")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("p")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v("v-t")]),a("span",{pre:!0,attrs:{class:"token attr-value"}},[a("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("'")]),t._v("hello"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("'")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token comment"}},[t._v("\x3c!-- keypath binding via data --\x3e")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("p")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v("v-t")]),a("span",{pre:!0,attrs:{class:"token attr-value"}},[a("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),t._v("path"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n"),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n")])])]),a("p",[t._v("Outputs:")]),t._v(" "),a("div",{staticClass:"language-html extra-class"},[a("pre",{pre:!0,attrs:{class:"language-html"}},[a("code",[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("div")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v("id")]),a("span",{pre:!0,attrs:{class:"token attr-value"}},[a("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),t._v("string-syntax"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("p")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("hi there!"),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("p")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("hi there!"),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n"),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n")])])]),a("h2",{attrs:{id:"object-syntax"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#object-syntax"}},[t._v("#")]),t._v(" Object syntax")]),t._v(" "),a("p",[t._v("You can use object syntax.")]),t._v(" "),a("p",[t._v("Javascript:")]),t._v(" "),a("div",{staticClass:"language-js extra-class"},[a("pre",{pre:!0,attrs:{class:"language-js"}},[a("code",[a("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("new")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token class-name"}},[t._v("Vue")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("i18n")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("new")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token class-name"}},[t._v("VueI18n")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("locale")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v("'en'")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("messages")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("en")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("hello")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v("'hi {name}!'")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("ja")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("hello")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v("'こんにちは、{name}!'")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("computed")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token function"}},[t._v("nickName")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("return")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v("'kazupon'")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("data")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("path")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v("'hello'")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),a("span",{pre:!0,attrs:{class:"token function"}},[t._v("$mount")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),a("span",{pre:!0,attrs:{class:"token string"}},[t._v("'#object-syntax'")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v("\n")])])]),a("p",[t._v("Templates:")]),t._v(" "),a("div",{staticClass:"language-html extra-class"},[a("pre",{pre:!0,attrs:{class:"language-html"}},[a("code",[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("div")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v("id")]),a("span",{pre:!0,attrs:{class:"token attr-value"}},[a("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),t._v("object-syntax"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token comment"}},[t._v("\x3c!-- literal --\x3e")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("p")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v("v-t")]),a("span",{pre:!0,attrs:{class:"token attr-value"}},[a("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),t._v("{ path: "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("'")]),t._v("hello"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("'")]),t._v(", locale: "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("'")]),t._v("ja"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("'")]),t._v(", args: { name: "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("'")]),t._v("kazupon"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("'")]),t._v(" } }"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token comment"}},[t._v("\x3c!-- data binding via data --\x3e")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("p")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v("v-t")]),a("span",{pre:!0,attrs:{class:"token attr-value"}},[a("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),t._v("{ path: path, args: { name: nickName } }"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n"),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n")])])]),a("p",[t._v("Outputs:")]),t._v(" "),a("div",{staticClass:"language-html extra-class"},[a("pre",{pre:!0,attrs:{class:"language-html"}},[a("code",[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("div")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v("id")]),a("span",{pre:!0,attrs:{class:"token attr-value"}},[a("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),t._v("object-syntax"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("p")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("こんにちは、kazupon!"),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("p")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("hi kazupon!"),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n"),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n")])])]),a("h2",{attrs:{id:"use-with-transitions"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#use-with-transitions"}},[t._v("#")]),t._v(" Use with transitions")]),t._v(" "),a("div",{staticClass:"custom-block tip"},[a("p",{staticClass:"custom-block-title"},[t._v("Support Version")]),t._v(" "),a("p",[t._v("🆕 8.7+")])]),t._v(" "),a("p",[t._v("When "),a("code",[t._v("v-t")]),t._v(" directive is applied to an element inside "),a("a",{attrs:{href:"https://vuejs.org/v2/api/#transition",target:"_blank",rel:"noopener noreferrer"}},[a("code",[t._v("")]),t._v(" component"),a("OutboundLink")],1),t._v(", you may notice that the translated message disappears during the transition. This behavior is related to the nature of the "),a("code",[t._v("")]),t._v(" component implementation – all directives in the disappearing element inside the "),a("code",[t._v("")]),t._v(" component will be destroyed "),a("strong",[t._v("before the transition starts")]),t._v(". This behavior may result in content flickering on short animations, but is most noticeable on long transitions.")]),t._v(" "),a("p",[t._v("To make sure directive content stays un-touched during a transition, just add the "),a("RouterLink",{attrs:{to:"/api/#v-t"}},[a("code",[t._v(".preserve")]),t._v(" modifier")]),t._v(" to the "),a("code",[t._v("v-t")]),t._v(" directive definition.")],1),t._v(" "),a("p",[t._v("Javascript:")]),t._v(" "),a("div",{staticClass:"language-js extra-class"},[a("pre",{pre:!0,attrs:{class:"language-js"}},[a("code",[a("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("new")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token class-name"}},[t._v("Vue")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("i18n")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("new")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token class-name"}},[t._v("VueI18n")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("locale")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v("'en'")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("messages")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("en")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("preserve")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v("'with preserve'")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("data")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("toggle")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token boolean"}},[t._v("true")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),a("span",{pre:!0,attrs:{class:"token function"}},[t._v("$mount")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),a("span",{pre:!0,attrs:{class:"token string"}},[t._v("'#in-transitions'")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v("\n")])])]),a("p",[t._v("Templates:")]),t._v(" "),a("div",{staticClass:"language-html extra-class"},[a("pre",{pre:!0,attrs:{class:"language-html"}},[a("code",[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("div")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v("id")]),a("span",{pre:!0,attrs:{class:"token attr-value"}},[a("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),t._v("in-transitions"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("transition")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v("name")]),a("span",{pre:!0,attrs:{class:"token attr-value"}},[a("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),t._v("fade"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("span")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v("v-if")]),a("span",{pre:!0,attrs:{class:"token attr-value"}},[a("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),t._v("toggle"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])]),t._v(" "),a("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v("v-t.preserve")]),a("span",{pre:!0,attrs:{class:"token attr-value"}},[a("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("'")]),t._v("preserve"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("'")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("button")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v("@click")]),a("span",{pre:!0,attrs:{class:"token attr-value"}},[a("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),t._v("toggle = !toggle"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("Toggle"),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n"),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n")])])]),a("p",[t._v("It is also possible to set global settings on the "),a("code",[t._v("VueI18n")]),t._v(" instance itself, which will affect all "),a("code",[t._v("v-t")]),t._v(" directives without modifier.")]),t._v(" "),a("p",[t._v("Javascript:")]),t._v(" "),a("div",{staticClass:"language-js extra-class"},[a("pre",{pre:!0,attrs:{class:"language-js"}},[a("code",[a("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("new")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token class-name"}},[t._v("Vue")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("i18n")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("new")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token class-name"}},[t._v("VueI18n")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("locale")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v("'en'")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("messages")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("en")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("preserve")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v("'with preserve'")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("preserveDirectiveContent")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token boolean"}},[t._v("true")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("data")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("toggle")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token boolean"}},[t._v("true")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),a("span",{pre:!0,attrs:{class:"token function"}},[t._v("$mount")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),a("span",{pre:!0,attrs:{class:"token string"}},[t._v("'#in-transitions'")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v("\n")])])]),a("p",[t._v("Templates:")]),t._v(" "),a("div",{staticClass:"language-html extra-class"},[a("pre",{pre:!0,attrs:{class:"language-html"}},[a("code",[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("div")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v("id")]),a("span",{pre:!0,attrs:{class:"token attr-value"}},[a("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),t._v("in-transitions"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("transition")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v("name")]),a("span",{pre:!0,attrs:{class:"token attr-value"}},[a("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),t._v("fade"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("span")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v("v-if")]),a("span",{pre:!0,attrs:{class:"token attr-value"}},[a("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),t._v("toggle"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])]),t._v(" "),a("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v("v-t")]),a("span",{pre:!0,attrs:{class:"token attr-value"}},[a("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("'")]),t._v("preserve"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("'")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("button")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v("@click")]),a("span",{pre:!0,attrs:{class:"token attr-value"}},[a("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),t._v("toggle = !toggle"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("Toggle"),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n"),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n")])])]),a("p",[t._v("About the above examples, see the "),a("a",{attrs:{href:"https://github.com/kazupon/vue-i18n/tree/dev/examples/directive",target:"_blank",rel:"noopener noreferrer"}},[t._v("example"),a("OutboundLink")],1)]),t._v(" "),a("h2",{attrs:{id:"t-vs-v-t"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#t-vs-v-t"}},[t._v("#")]),t._v(" "),a("code",[t._v("$t")]),t._v(" vs "),a("code",[t._v("v-t")])]),t._v(" "),a("h3",{attrs:{id:"t"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#t"}},[t._v("#")]),t._v(" "),a("code",[t._v("$t")])]),t._v(" "),a("p",[a("code",[t._v("$t")]),t._v(" is an extended Vue instance method. It has the following pros and cons:")]),t._v(" "),a("h4",{attrs:{id:"pros"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#pros"}},[t._v("#")]),t._v(" Pros")]),t._v(" "),a("p",[t._v("You can "),a("strong",[t._v("flexibly")]),t._v(" use mustache syntax "),a("code",[t._v("{{}}")]),t._v(" in templates and also computed props and methods in Vue instance.")]),t._v(" "),a("h4",{attrs:{id:"cons"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#cons"}},[t._v("#")]),t._v(" Cons")]),t._v(" "),a("p",[a("code",[t._v("$t")]),t._v(" is executed "),a("strong",[t._v("every time")]),t._v(" when re-render occurs, so it does have translation costs.")]),t._v(" "),a("h3",{attrs:{id:"v-t"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#v-t"}},[t._v("#")]),t._v(" "),a("code",[t._v("v-t")])]),t._v(" "),a("p",[a("code",[t._v("v-t")]),t._v(" is a custom directive. It has the following pros and cons:")]),t._v(" "),a("h4",{attrs:{id:"pros-2"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#pros-2"}},[t._v("#")]),t._v(" Pros")]),t._v(" "),a("p",[a("code",[t._v("v-t")]),t._v(" has "),a("strong",[t._v("better performance")]),t._v(" than the "),a("code",[t._v("$t")]),t._v(" method due to its cache with the custom directive, when translated once. Also, pre-translation is possible with the Vue compiler module which was provided by "),a("a",{attrs:{href:"https://github.com/kazupon/vue-i18n-extensions",target:"_blank",rel:"noopener noreferrer"}},[a("code",[t._v("vue-i18n-extensions")]),a("OutboundLink")],1),t._v(".")]),t._v(" "),a("p",[t._v("Therefore it's possible to make "),a("strong",[t._v("more performance optimizations")]),t._v(".")]),t._v(" "),a("h4",{attrs:{id:"cons-2"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#cons-2"}},[t._v("#")]),t._v(" Cons")]),t._v(" "),a("p",[a("code",[t._v("v-t")]),t._v(" cannot be flexibly used like "),a("code",[t._v("$t")]),t._v(", it's rather "),a("strong",[t._v("complex")]),t._v(". The translated content with "),a("code",[t._v("v-t")]),t._v(" is inserted into the "),a("code",[t._v("textContent")]),t._v(" of the element. Also, when you use server-side rendering, you need to set the "),a("a",{attrs:{href:"https://github.com/kazupon/vue-i18n-extensions#directive-v-t-custom-directive-for-server-side",target:"_blank",rel:"noopener noreferrer"}},[t._v("custom directive"),a("OutboundLink")],1),t._v(" to "),a("code",[t._v("directives")]),t._v(" option of the "),a("code",[t._v("createRenderer")]),t._v(" function.")])])}),[],!1,null,null,null);s.default=e.exports}}]); \ No newline at end of file diff --git a/assets/js/14.7b4ef339.js b/assets/js/14.7b4ef339.js new file mode 100644 index 000000000..0981814d5 --- /dev/null +++ b/assets/js/14.7b4ef339.js @@ -0,0 +1 @@ +(window.webpackJsonp=window.webpackJsonp||[]).push([[14],{463:function(t,a,s){"use strict";s.r(a);var e=s(44),n=Object(e.a)({},(function(){var t=this,a=t.$createElement,s=t._self._c||a;return s("ContentSlotsDistributor",{attrs:{"slot-key":t.$parent.slotKey}},[s("h1",{attrs:{id:"fallback-localization"}},[s("a",{staticClass:"header-anchor",attrs:{href:"#fallback-localization"}},[t._v("#")]),t._v(" Fallback localization")]),t._v(" "),s("p",[s("em",[t._v("Summary: Use "),s("code",[t._v("fallbackLocale: ''")]),t._v(" to choose which language to use when your preferred language lacks a translation.")])]),t._v(" "),s("h2",{attrs:{id:"implicit-fallback-using-locales"}},[s("a",{staticClass:"header-anchor",attrs:{href:"#implicit-fallback-using-locales"}},[t._v("#")]),t._v(" Implicit fallback using locales")]),t._v(" "),s("p",[t._v("If a "),s("code",[t._v("locale")]),t._v(" is given containing a territory and an optional dialect, the implicit fallback is activated automatically.")]),t._v(" "),s("p",[t._v("For example "),s("code",[t._v("de-DE-bavarian")]),t._v(" would fallback")]),t._v(" "),s("ol",[s("li",[s("code",[t._v("de-DE-bavarian")])]),t._v(" "),s("li",[s("code",[t._v("de-DE")])]),t._v(" "),s("li",[s("code",[t._v("de")])])]),t._v(" "),s("p",[t._v("To suppress the automatic fallback, add the postfix exclamation mark "),s("code",[t._v("!")]),t._v(", for example "),s("code",[t._v("de-DE!")])]),t._v(" "),s("h2",{attrs:{id:"explicit-fallback-with-one-locale"}},[s("a",{staticClass:"header-anchor",attrs:{href:"#explicit-fallback-with-one-locale"}},[t._v("#")]),t._v(" Explicit fallback with one locale")]),t._v(" "),s("p",[t._v("Sometimes some items will not be translated into some languages. In this example, the item "),s("code",[t._v("hello")]),t._v(" is available in English but not Japanese:")]),t._v(" "),s("div",{staticClass:"language-js extra-class"},[s("pre",{pre:!0,attrs:{class:"language-js"}},[s("code",[s("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("const")]),t._v(" messages "),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("en")]),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("hello")]),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token string"}},[t._v("'Hello, world!'")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("ja")]),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// Localization without translation to `hello`")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n")])])]),s("p",[t._v("If you want to use (say) "),s("code",[t._v("en")]),t._v(" items when an item is not available in your desired locale, set the "),s("code",[t._v("fallbackLocale")]),t._v(" option in the VueI18n constructor:")]),t._v(" "),s("div",{staticClass:"language-js extra-class"},[s("pre",{pre:!0,attrs:{class:"language-js"}},[s("code",[s("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("const")]),t._v(" i18n "),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("new")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token class-name"}},[t._v("VueI18n")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("locale")]),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token string"}},[t._v("'ja'")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("fallbackLocale")]),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token string"}},[t._v("'en'")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n messages\n"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v("\n")])])]),s("p",[t._v("Template:")]),t._v(" "),s("div",{staticClass:"language-html extra-class"},[s("pre",{pre:!0,attrs:{class:"language-html"}},[s("code",[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("p")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("{{ $t('hello') }}"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n")])])]),s("p",[t._v("Output:")]),t._v(" "),s("div",{staticClass:"language-html extra-class"},[s("pre",{pre:!0,attrs:{class:"language-html"}},[s("code",[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("p")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("Hello, world!"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n")])])]),s("p",[t._v("By default, falling back to "),s("code",[t._v("fallbackLocale")]),t._v(" generates two console warnings:")]),t._v(" "),s("div",{staticClass:"language- extra-class"},[s("pre",{pre:!0,attrs:{class:"language-text"}},[s("code",[t._v("[vue-i18n] Value of key 'hello' is not a string!\n[vue-i18n] Fall back to translate the keypath 'hello' with 'en' locale.\n")])])]),s("p",[t._v("To suppress these warnings (while keeping those which warn of the total absence of translation for the given key) set "),s("code",[t._v("silentFallbackWarn: true")]),t._v(" when initializing the "),s("code",[t._v("VueI18n")]),t._v(" instance.")]),t._v(" "),s("h2",{attrs:{id:"explicit-fallback-with-an-array-of-locales"}},[s("a",{staticClass:"header-anchor",attrs:{href:"#explicit-fallback-with-an-array-of-locales"}},[t._v("#")]),t._v(" Explicit fallback with an array of locales")]),t._v(" "),s("p",[t._v("It is possible to set more than one fallback locale by using an array of locales. For example")]),t._v(" "),s("div",{staticClass:"language-javascript extra-class"},[s("pre",{pre:!0,attrs:{class:"language-javascript"}},[s("code",[s("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("fallbackLocale")]),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("[")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token string"}},[t._v("'fr'")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token string"}},[t._v("'en'")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("]")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n")])])]),s("h2",{attrs:{id:"explicit-fallback-with-decision-maps"}},[s("a",{staticClass:"header-anchor",attrs:{href:"#explicit-fallback-with-decision-maps"}},[t._v("#")]),t._v(" Explicit fallback with decision maps")]),t._v(" "),s("p",[t._v("If more complex decision maps for fallback locales are required, it is possible to define decision maps with according fallback locales.\nUsing the following decision map")]),t._v(" "),s("div",{staticClass:"language-javascript extra-class"},[s("pre",{pre:!0,attrs:{class:"language-javascript"}},[s("code",[s("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("fallbackLocale")]),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token comment"}},[t._v("/* 1 */")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token string"}},[t._v("'de-CH'")]),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("[")]),s("span",{pre:!0,attrs:{class:"token string"}},[t._v("'fr'")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token string"}},[t._v("'it'")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("]")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token comment"}},[t._v("/* 2 */")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token string"}},[t._v("'zh-Hant'")]),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("[")]),s("span",{pre:!0,attrs:{class:"token string"}},[t._v("'zh-Hans'")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("]")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token comment"}},[t._v("/* 3 */")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token string"}},[t._v("'es-CL'")]),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("[")]),s("span",{pre:!0,attrs:{class:"token string"}},[t._v("'es-AR'")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("]")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token comment"}},[t._v("/* 4 */")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token string"}},[t._v("'es'")]),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("[")]),s("span",{pre:!0,attrs:{class:"token string"}},[t._v("'en-GB'")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("]")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token comment"}},[t._v("/* 5 */")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token string"}},[t._v("'pt'")]),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("[")]),s("span",{pre:!0,attrs:{class:"token string"}},[t._v("'es-AR'")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("]")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token comment"}},[t._v("/* 6 */")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token string"}},[t._v("'default'")]),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("[")]),s("span",{pre:!0,attrs:{class:"token string"}},[t._v("'en'")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token string"}},[t._v("'da'")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("]")]),t._v("\n"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n")])])]),s("p",[t._v("will result in the following fallback chains")]),t._v(" "),s("table",[s("thead",[s("tr",[s("th",[t._v("locale")]),t._v(" "),s("th",[t._v("fallback chains")])])]),t._v(" "),s("tbody",[s("tr",[s("td",[s("code",[t._v("'de-CH'")])]),t._v(" "),s("td",[t._v("de-CH > fr > it > en > da")])]),t._v(" "),s("tr",[s("td",[s("code",[t._v("'de'")])]),t._v(" "),s("td",[t._v("de > en > da")])]),t._v(" "),s("tr",[s("td",[s("code",[t._v("'zh-Hant'")])]),t._v(" "),s("td",[t._v("zh-Hant > zh-Hans > zh > en > da")])]),t._v(" "),s("tr",[s("td",[s("code",[t._v("'es-SP'")])]),t._v(" "),s("td",[t._v("es-SP > es > en-GB > en > da")])]),t._v(" "),s("tr",[s("td",[s("code",[t._v("'es-SP!'")])]),t._v(" "),s("td",[t._v("es-SP > en > da")])]),t._v(" "),s("tr",[s("td",[s("code",[t._v("'fr'")])]),t._v(" "),s("td",[t._v("fr > en > da")])]),t._v(" "),s("tr",[s("td",[s("code",[t._v("'pt-BR'")])]),t._v(" "),s("td",[t._v("pt-BR > pt > es-AR > es > en-GB > en > da")])]),t._v(" "),s("tr",[s("td",[s("code",[t._v("'es-CL'")])]),t._v(" "),s("td",[t._v("es-CL > es-AR > es > en-GB > en > da")])])])]),t._v(" "),s("h2",{attrs:{id:"fallback-interpolation"}},[s("a",{staticClass:"header-anchor",attrs:{href:"#fallback-interpolation"}},[t._v("#")]),t._v(" Fallback interpolation")]),t._v(" "),s("p",[s("em",[t._v("Summary: Set "),s("code",[t._v("formatFallbackMessages: true")]),t._v(" to do template interpolation on translation keys when your language lacks a translation for a key.")])]),t._v(" "),s("p",[t._v("Since the keys to the translations are strings, you can use a user-readable message (for a particular language) as a key.\nE.g.")]),t._v(" "),s("div",{staticClass:"language-javascript extra-class"},[s("pre",{pre:!0,attrs:{class:"language-javascript"}},[s("code",[s("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("const")]),t._v(" messages "),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("ja")]),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token string-property property"}},[t._v("'Hello, world!'")]),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token string"}},[t._v("'こんにちは、世界!'")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n")])])]),s("p",[t._v('This is useful because you don\'t have to specify a translation for the string "Hello, world!" into English.')]),t._v(" "),s("p",[t._v("In fact, you can even include template parameters in a key. Together with "),s("code",[t._v("formatFallbackMessages: true")]),t._v(', this lets you skip writing templates for your "base" language; the keys '),s("em",[t._v("are")]),t._v(" your templates.")]),t._v(" "),s("div",{staticClass:"language-javascript extra-class"},[s("pre",{pre:!0,attrs:{class:"language-javascript"}},[s("code",[s("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("const")]),t._v(" messages "),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("ru")]),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token string-property property"}},[t._v("'Hello {name}'")]),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token string"}},[t._v("'Здравствуйте {name}'")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n\n"),s("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("const")]),t._v(" i18n "),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("new")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token class-name"}},[t._v("VueI18n")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("locale")]),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token string"}},[t._v("'ru'")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("fallbackLocale")]),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token string"}},[t._v("'en'")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("formatFallbackMessages")]),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token boolean"}},[t._v("true")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n messages\n"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v("\n")])])]),s("p",[t._v("When the template is as below:")]),t._v(" "),s("div",{staticClass:"language-html extra-class"},[s("pre",{pre:!0,attrs:{class:"language-html"}},[s("code",[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("p")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("{{ $t('Hello {name}', { name: 'John' }}) }}"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("p")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("{{ $t('The weather today is {condition}!', { condition: 'sunny' }) }}"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n")])])]),s("p",[t._v("The following will be output:")]),t._v(" "),s("div",{staticClass:"language-html extra-class"},[s("pre",{pre:!0,attrs:{class:"language-html"}},[s("code",[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("p")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("Здравствуйте, John"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("p")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("The weather today is sunny!"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n")])])])])}),[],!1,null,null,null);a.default=n.exports}}]); \ No newline at end of file diff --git a/assets/js/15.86b2b656.js b/assets/js/15.86b2b656.js new file mode 100644 index 000000000..b3864c063 --- /dev/null +++ b/assets/js/15.86b2b656.js @@ -0,0 +1 @@ +(window.webpackJsonp=window.webpackJsonp||[]).push([[15],{467:function(t,s,a){"use strict";a.r(s);var n=a(44),e=Object(n.a)({},(function(){var t=this,s=t.$createElement,a=t._self._c||s;return a("ContentSlotsDistributor",{attrs:{"slot-key":t.$parent.slotKey}},[a("h1",{attrs:{id:"formatting"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#formatting"}},[t._v("#")]),t._v(" Formatting")]),t._v(" "),a("h2",{attrs:{id:"named-formatting"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#named-formatting"}},[t._v("#")]),t._v(" Named formatting")]),t._v(" "),a("p",[t._v("Locale messages:")]),t._v(" "),a("div",{staticClass:"language-js extra-class"},[a("pre",{pre:!0,attrs:{class:"language-js"}},[a("code",[a("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("const")]),t._v(" messages "),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("en")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("message")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("hello")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v("'{msg} world'")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n")])])]),a("p",[t._v("Template:")]),t._v(" "),a("div",{staticClass:"language-html extra-class"},[a("pre",{pre:!0,attrs:{class:"language-html"}},[a("code",[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("p")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("{{ $t('message.hello', { msg: 'hello' }) }}"),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n")])])]),a("p",[t._v("Output:")]),t._v(" "),a("div",{staticClass:"language-html extra-class"},[a("pre",{pre:!0,attrs:{class:"language-html"}},[a("code",[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("p")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("hello world"),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n")])])]),a("h2",{attrs:{id:"list-formatting"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#list-formatting"}},[t._v("#")]),t._v(" List formatting")]),t._v(" "),a("p",[t._v("Locale messages:")]),t._v(" "),a("div",{staticClass:"language-js extra-class"},[a("pre",{pre:!0,attrs:{class:"language-js"}},[a("code",[a("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("const")]),t._v(" messages "),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("en")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("message")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("hello")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v("'{0} world'")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n")])])]),a("p",[t._v("Template:")]),t._v(" "),a("div",{staticClass:"language-html extra-class"},[a("pre",{pre:!0,attrs:{class:"language-html"}},[a("code",[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("p")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("{{ $t('message.hello', ['hello']) }}"),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n")])])]),a("p",[t._v("Output:")]),t._v(" "),a("div",{staticClass:"language-html extra-class"},[a("pre",{pre:!0,attrs:{class:"language-html"}},[a("code",[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("p")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("hello world"),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n")])])]),a("p",[t._v("List formatting also accepts array-like objects:")]),t._v(" "),a("div",{staticClass:"language-html extra-class"},[a("pre",{pre:!0,attrs:{class:"language-html"}},[a("code",[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("p")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("{{ $t('message.hello', {'0': 'hello'}) }}"),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n")])])]),a("p",[t._v("Output:")]),t._v(" "),a("div",{staticClass:"language-html extra-class"},[a("pre",{pre:!0,attrs:{class:"language-html"}},[a("code",[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("p")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("hello world"),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n")])])]),a("h2",{attrs:{id:"html-formatting"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#html-formatting"}},[t._v("#")]),t._v(" HTML formatting")]),t._v(" "),a("div",{staticClass:"custom-block warning"},[a("p",{staticClass:"custom-block-title"},[t._v("Notice")]),t._v(" "),a("p",[t._v("⚠️ Dynamically localizing arbitrary HTML on your website can be very dangerous because it can easily lead to XSS vulnerabilities. Only use HTML interpolation on trusted content and never on user-provided content.")]),t._v(" "),a("p",[t._v("We recommended using the "),a("RouterLink",{attrs:{to:"/guide/interpolation.html"}},[t._v("component interpolation")]),t._v(" feature.")],1)]),t._v(" "),a("div",{staticClass:"custom-block warning"},[a("p",{staticClass:"custom-block-title"},[t._v("Notice")]),t._v(" "),a("blockquote",[a("p",[t._v("🆕 8.11+")])]),t._v(" "),a("p",[t._v("You can control the use of HTML formatting. see the detail "),a("code",[t._v("warnHtmlInMessage")]),t._v(" constructor option and property API.")])]),t._v(" "),a("p",[t._v("In some cases you might want to render your translation as an HTML message and not a static string.")]),t._v(" "),a("div",{staticClass:"language-js extra-class"},[a("pre",{pre:!0,attrs:{class:"language-js"}},[a("code",[a("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("const")]),t._v(" messages "),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("en")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("message")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("hello")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v("'hello
world'")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n")])])]),a("p",[t._v("Template:")]),t._v(" "),a("div",{staticClass:"language-html extra-class"},[a("pre",{pre:!0,attrs:{class:"language-html"}},[a("code",[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("p")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v("v-html")]),a("span",{pre:!0,attrs:{class:"token attr-value"}},[a("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),t._v("$t("),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("'")]),t._v("message.hello"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("'")]),t._v(")"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n")])])]),a("p",[t._v("Output (instead of the pre-formatted message )")]),t._v(" "),a("div",{staticClass:"language-html extra-class"},[a("pre",{pre:!0,attrs:{class:"language-html"}},[a("code",[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("p")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("hello\n"),a("span",{pre:!0,attrs:{class:"token comment"}},[t._v("\x3c!--
exists but is rendered as html and not a string--\x3e")]),t._v("\nworld"),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n")])])]),a("h2",{attrs:{id:"support-ruby-on-rails-i18n-format"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#support-ruby-on-rails-i18n-format"}},[t._v("#")]),t._v(" Support ruby on rails i18n format")]),t._v(" "),a("p",[t._v("Locale messages:")]),t._v(" "),a("div",{staticClass:"language-js extra-class"},[a("pre",{pre:!0,attrs:{class:"language-js"}},[a("code",[a("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("const")]),t._v(" messages "),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("en")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("message")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("hello")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v("'%{msg} world'")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n")])])]),a("p",[t._v("Template:")]),t._v(" "),a("div",{staticClass:"language-html extra-class"},[a("pre",{pre:!0,attrs:{class:"language-html"}},[a("code",[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("p")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("{{ $t('message.hello', { msg: 'hello' }) }}"),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n")])])]),a("p",[t._v("Output:")]),t._v(" "),a("div",{staticClass:"language-html extra-class"},[a("pre",{pre:!0,attrs:{class:"language-html"}},[a("code",[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("p")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("hello world"),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n")])])]),a("h2",{attrs:{id:"custom-formatting"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#custom-formatting"}},[t._v("#")]),t._v(" Custom formatting")]),t._v(" "),a("p",[t._v("Sometimes, you may need to translate using custom formatting (e.g. "),a("a",{attrs:{href:"http://userguide.icu-project.org/formatparse/messages",target:"_blank",rel:"noopener noreferrer"}},[t._v("ICU message syntax"),a("OutboundLink")],1),t._v(").")]),t._v(" "),a("p",[t._v("You can do that with a custom formatter that implements the "),a("a",{attrs:{href:"https://github.com/kazupon/vue-i18n/blob/dev/decls/i18n.js#L145-L147",target:"_blank",rel:"noopener noreferrer"}},[t._v("Formatter Interface"),a("OutboundLink")],1),t._v(".")]),t._v(" "),a("p",[t._v("The following custom formatter with ES2015 class syntax:")]),t._v(" "),a("div",{staticClass:"language-js extra-class"},[a("pre",{pre:!0,attrs:{class:"language-js"}},[a("code",[a("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// Custom Formatter implementation")]),t._v("\n"),a("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("class")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token class-name"}},[t._v("CustomFormatter")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token function"}},[t._v("constructor")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),a("span",{pre:!0,attrs:{class:"token parameter"}},[t._v("options")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// ...")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n\n "),a("span",{pre:!0,attrs:{class:"token comment"}},[t._v("//")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// interpolate")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token comment"}},[t._v("//")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// @param {string} message")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// string of list or named format.")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// e.g.")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// - named formatting: 'Hi {name}'")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// - list formatting: 'Hi {0}'")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token comment"}},[t._v("//")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// @param {Object | Array} values")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// values of `message` interpolation.")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// passed values with `$t`, `$tc` and `i18n` functional component.")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// e.g.")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// - $t('hello', { name: 'kazupon' }) -> passed values: Object `{ name: 'kazupon' }`")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// - $t('hello', ['kazupon']) -> passed values: Array `['kazupon']`")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// - `i18n` functional component (component interpolation)")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token comment"}},[t._v('// ')]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token comment"}},[t._v("//

kazupon

")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token comment"}},[t._v("//

how are you?

")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token comment"}},[t._v("//
")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// -> passed values: Array (included VNode):")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// `[VNode{ tag: 'p', text: 'kazupon', ...}, VNode{ tag: 'p', text: 'how are you?', ...}]`")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token comment"}},[t._v("//")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// @return {Array}")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// interpolated values. you need to return the following:")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// - array of string, when is using `$t` or `$tc`.")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// - array included VNode object, when is using `i18n` functional component.")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token comment"}},[t._v("//")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token function"}},[t._v("interpolate")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),a("span",{pre:!0,attrs:{class:"token parameter"}},[t._v("message"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" values")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// implement interpolation logic here")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// ...")]),t._v("\n\n "),a("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// return the interpolated array")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("return")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("[")]),a("span",{pre:!0,attrs:{class:"token string"}},[t._v("'resolved message string'")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("]")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n\n"),a("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// register with `formatter` option")]),t._v("\n"),a("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("const")]),t._v(" i18n "),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("new")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token class-name"}},[t._v("VueI18n")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("locale")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v("'en-US'")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("formatter")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("new")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token class-name"}},[t._v("CustomFormatter")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),a("span",{pre:!0,attrs:{class:"token comment"}},[t._v("/* here the constructor options */")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("messages")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token string-property property"}},[t._v("'en-US'")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// ...")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// ...")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v("\n\n"),a("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// Run!")]),t._v("\n"),a("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("new")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token class-name"}},[t._v("Vue")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v(" i18n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),a("span",{pre:!0,attrs:{class:"token function"}},[t._v("$mount")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),a("span",{pre:!0,attrs:{class:"token string"}},[t._v("'#app'")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v("\n")])])]),a("p",[t._v("You can check "),a("a",{attrs:{href:"https://github.com/kazupon/vue-i18n/tree/dev/examples/formatting/custom",target:"_blank",rel:"noopener noreferrer"}},[t._v("the custom formatter official example"),a("OutboundLink")],1),t._v(".")])])}),[],!1,null,null,null);s.default=e.exports}}]); \ No newline at end of file diff --git a/assets/js/16.b1f10e5a.js b/assets/js/16.b1f10e5a.js new file mode 100644 index 000000000..ebe07faba --- /dev/null +++ b/assets/js/16.b1f10e5a.js @@ -0,0 +1 @@ +(window.webpackJsonp=window.webpackJsonp||[]).push([[16],{465:function(t,s,a){"use strict";a.r(s);var n=a(44),e=Object(n.a)({},(function(){var t=this,s=t.$createElement,a=t._self._c||s;return a("ContentSlotsDistributor",{attrs:{"slot-key":t.$parent.slotKey}},[a("h1",{attrs:{id:"hot-reloading"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#hot-reloading"}},[t._v("#")]),t._v(" Hot reloading")]),t._v(" "),a("p",[t._v("You can use Webpack's "),a("a",{attrs:{href:"https://webpack.js.org/concepts/hot-module-replacement/",target:"_blank",rel:"noopener noreferrer"}},[t._v("Hot Module Replacement"),a("OutboundLink")],1),t._v(" (HMR) feature to watch for changes in localization files and hot reload changes into your application.")]),t._v(" "),a("h2",{attrs:{id:"basic-example"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#basic-example"}},[t._v("#")]),t._v(" Basic example")]),t._v(" "),a("p",[t._v("If you only use a static set of locales, you can hot reload those locales explicitly:")]),t._v(" "),a("div",{staticClass:"language-js extra-class"},[a("pre",{pre:!0,attrs:{class:"language-js"}},[a("code",[a("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("import")]),t._v(" Vue "),a("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("from")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v('"vue"')]),t._v("\n"),a("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("import")]),t._v(" VueI18n "),a("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("from")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v('"vue-i18n"')]),t._v("\n"),a("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("import")]),t._v(" en "),a("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("from")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v("'./en'")]),t._v("\n"),a("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("import")]),t._v(" ja "),a("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("from")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v("'./ja'")]),t._v("\n\n"),a("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("const")]),t._v(" messages "),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n en"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n ja\n"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n\n"),a("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// VueI18n instance")]),t._v("\n"),a("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("const")]),t._v(" i18n "),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("new")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token class-name"}},[t._v("VueI18n")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("locale")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v("'en'")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n messages\n"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v("\n\n"),a("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// Run app")]),t._v("\n"),a("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("const")]),t._v(" app "),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("new")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token class-name"}},[t._v("Vue")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n i18n"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// ...")]),t._v("\n"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),a("span",{pre:!0,attrs:{class:"token function"}},[t._v("$mount")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),a("span",{pre:!0,attrs:{class:"token string"}},[t._v("'#app'")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v("\n\n"),a("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// Hot updates")]),t._v("\n"),a("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("if")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v("module"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("hot"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n module"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("hot"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),a("span",{pre:!0,attrs:{class:"token function"}},[t._v("accept")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("[")]),a("span",{pre:!0,attrs:{class:"token string"}},[t._v("'./en'")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v("'./ja'")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("]")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("function")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n i18n"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),a("span",{pre:!0,attrs:{class:"token function"}},[t._v("setLocaleMessage")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),a("span",{pre:!0,attrs:{class:"token string"}},[t._v("'en'")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token function"}},[t._v("require")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),a("span",{pre:!0,attrs:{class:"token string"}},[t._v("'./en'")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("default"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v("\n i18n"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),a("span",{pre:!0,attrs:{class:"token function"}},[t._v("setLocaleMessage")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),a("span",{pre:!0,attrs:{class:"token string"}},[t._v("'ja'")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token function"}},[t._v("require")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),a("span",{pre:!0,attrs:{class:"token string"}},[t._v("'./ja'")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("default"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// Or the following hot updates via $i18n property")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// app.$i18n.setLocaleMessage('en', require('./en').default)")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// app.$i18n.setLocaleMessage('ja', require('./ja').default)")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v("\n"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n")])])]),a("h2",{attrs:{id:"advanced-example"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#advanced-example"}},[t._v("#")]),t._v(" Advanced example")]),t._v(" "),a("p",[t._v("If you want to support a changing set of locales, you can hot reload those locales dynamically using "),a("code",[t._v("require.context")]),t._v(":")]),t._v(" "),a("div",{staticClass:"language-js extra-class"},[a("pre",{pre:!0,attrs:{class:"language-js"}},[a("code",[a("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("import")]),t._v(" Vue "),a("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("from")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v('"vue"')]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n"),a("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("import")]),t._v(" VueI18n "),a("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("from")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v('"vue-i18n"')]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n\nVue"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),a("span",{pre:!0,attrs:{class:"token function"}},[t._v("use")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v("VueI18n"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n\n"),a("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// Load all locales and remember context")]),t._v("\n"),a("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("function")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token function"}},[t._v("loadMessages")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("const")]),t._v(" context "),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" require"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),a("span",{pre:!0,attrs:{class:"token function"}},[t._v("context")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),a("span",{pre:!0,attrs:{class:"token string"}},[t._v('"./locales"')]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token boolean"}},[t._v("true")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token regex"}},[a("span",{pre:!0,attrs:{class:"token regex-delimiter"}},[t._v("/")]),a("span",{pre:!0,attrs:{class:"token regex-source language-regex"}},[t._v("[a-z0-9-_]+\\.json$")]),a("span",{pre:!0,attrs:{class:"token regex-delimiter"}},[t._v("/")]),a("span",{pre:!0,attrs:{class:"token regex-flags"}},[t._v("i")])]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n\n "),a("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("const")]),t._v(" messages "),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" context\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),a("span",{pre:!0,attrs:{class:"token function"}},[t._v("keys")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),a("span",{pre:!0,attrs:{class:"token function"}},[t._v("map")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),a("span",{pre:!0,attrs:{class:"token parameter"}},[t._v("key")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=>")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v(" key"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("locale")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" key"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),a("span",{pre:!0,attrs:{class:"token function"}},[t._v("match")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),a("span",{pre:!0,attrs:{class:"token regex"}},[a("span",{pre:!0,attrs:{class:"token regex-delimiter"}},[t._v("/")]),a("span",{pre:!0,attrs:{class:"token regex-source language-regex"}},[t._v("[a-z0-9-_]+")]),a("span",{pre:!0,attrs:{class:"token regex-delimiter"}},[t._v("/")]),a("span",{pre:!0,attrs:{class:"token regex-flags"}},[t._v("i")])]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("[")]),a("span",{pre:!0,attrs:{class:"token number"}},[t._v("0")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("]")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),a("span",{pre:!0,attrs:{class:"token function"}},[t._v("reduce")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),a("span",{pre:!0,attrs:{class:"token parameter"}},[t._v("messages"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v(" key"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" locale "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")])]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=>")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v("...")]),t._v("messages"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("[")]),t._v("locale"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("]")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token function"}},[t._v("context")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v("key"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n\n "),a("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("return")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v(" context"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" messages "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n\n"),a("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("const")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v(" context"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" messages "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token function"}},[t._v("loadMessages")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n\n"),a("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// VueI18n instance")]),t._v("\n"),a("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("const")]),t._v(" i18n "),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("new")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token class-name"}},[t._v("VueI18n")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("locale")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v('"en"')]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n messages"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n\n"),a("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// Run app")]),t._v("\n"),a("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("const")]),t._v(" app "),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("new")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token class-name"}},[t._v("Vue")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n i18n"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// ...")]),t._v("\n"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),a("span",{pre:!0,attrs:{class:"token function"}},[t._v("$mount")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),a("span",{pre:!0,attrs:{class:"token string"}},[t._v("'#app'")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n\n"),a("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// Hot updates")]),t._v("\n"),a("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("if")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v("module"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("hot"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n module"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("hot"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),a("span",{pre:!0,attrs:{class:"token function"}},[t._v("accept")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v("context"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("id"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=>")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("const")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("messages")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" newMessages "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token function"}},[t._v("loadMessages")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n\n Object"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),a("span",{pre:!0,attrs:{class:"token function"}},[t._v("keys")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v("newMessages"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),a("span",{pre:!0,attrs:{class:"token function"}},[t._v("filter")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),a("span",{pre:!0,attrs:{class:"token parameter"}},[t._v("locale")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=>")]),t._v(" messages"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("[")]),t._v("locale"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("]")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v("!==")]),t._v(" newMessages"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("[")]),t._v("locale"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("]")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),a("span",{pre:!0,attrs:{class:"token function"}},[t._v("forEach")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),a("span",{pre:!0,attrs:{class:"token parameter"}},[t._v("locale")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=>")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n messages"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("[")]),t._v("locale"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("]")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" newMessages"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("[")]),t._v("locale"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("]")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n i18n"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),a("span",{pre:!0,attrs:{class:"token function"}},[t._v("setLocaleMessage")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v("locale"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" messages"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("[")]),t._v("locale"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("]")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n")])])])])}),[],!1,null,null,null);s.default=e.exports}}]); \ No newline at end of file diff --git a/assets/js/17.91caebad.js b/assets/js/17.91caebad.js new file mode 100644 index 000000000..45ac7e5b7 --- /dev/null +++ b/assets/js/17.91caebad.js @@ -0,0 +1 @@ +(window.webpackJsonp=window.webpackJsonp||[]).push([[17],{466:function(t,a,s){"use strict";s.r(a);var n=s(44),e=Object(n.a)({},(function(){var t=this,a=t.$createElement,s=t._self._c||a;return s("ContentSlotsDistributor",{attrs:{"slot-key":t.$parent.slotKey}},[s("h1",{attrs:{id:"component-interpolation"}},[s("a",{staticClass:"header-anchor",attrs:{href:"#component-interpolation"}},[t._v("#")]),t._v(" Component interpolation")]),t._v(" "),s("h2",{attrs:{id:"basic-usage"}},[s("a",{staticClass:"header-anchor",attrs:{href:"#basic-usage"}},[t._v("#")]),t._v(" Basic Usage")]),t._v(" "),s("div",{staticClass:"custom-block tip"},[s("p",{staticClass:"custom-block-title"},[t._v("Support Version")]),t._v(" "),s("p",[t._v("🆕 7.0+")])]),t._v(" "),s("p",[t._v("Sometimes, we need to localize with a locale message that was included in a HTML tag or component. For example:")]),t._v(" "),s("div",{staticClass:"language-html extra-class"},[s("pre",{pre:!0,attrs:{class:"language-html"}},[s("code",[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("p")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("I accept xxx "),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("a")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v("href")]),s("span",{pre:!0,attrs:{class:"token attr-value"}},[s("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),t._v("/term"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("Terms of Service Agreement"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n")])])]),s("p",[t._v("In the above message, if you use "),s("code",[t._v("$t")]),t._v(", you will probably try to compose the following locale messages:")]),t._v(" "),s("div",{staticClass:"language-js extra-class"},[s("pre",{pre:!0,attrs:{class:"language-js"}},[s("code",[s("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("const")]),t._v(" messages "),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("en")]),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("term1")]),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token string"}},[t._v("'I Accept xxx\\'s'")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("term2")]),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token string"}},[t._v("'Terms of Service Agreement'")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n")])])]),s("p",[t._v("And your localized template may look like this:")]),t._v(" "),s("div",{staticClass:"language-html extra-class"},[s("pre",{pre:!0,attrs:{class:"language-html"}},[s("code",[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("p")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("{{ $t('term1') }}"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("a")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v("href")]),s("span",{pre:!0,attrs:{class:"token attr-value"}},[s("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),t._v("/term"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("{{ $t('term2') }}"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n")])])]),s("p",[t._v("Output:")]),t._v(" "),s("div",{staticClass:"language-html extra-class"},[s("pre",{pre:!0,attrs:{class:"language-html"}},[s("code",[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("p")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("I accept xxx "),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("a")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v("href")]),s("span",{pre:!0,attrs:{class:"token attr-value"}},[s("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),t._v("/term"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("Terms of Service Agreement"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n")])])]),s("p",[t._v("This is very cumbersome, and if you configure the "),s("code",[t._v("")]),t._v(" tag in a locale message, there is a possibility of XSS vulnerabilities due to localizing with\n"),s("code",[t._v("v-html=\"$t('term')\"")]),t._v(".")]),t._v(" "),s("p",[t._v("You can avoid it using the "),s("code",[t._v("i18n")]),t._v(" functional component. For example:")]),t._v(" "),s("div",{staticClass:"language-html extra-class"},[s("pre",{pre:!0,attrs:{class:"language-html"}},[s("code",[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("div")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v("id")]),s("span",{pre:!0,attrs:{class:"token attr-value"}},[s("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),t._v("app"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token comment"}},[t._v("\x3c!-- ... --\x3e")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("i18n")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v("path")]),s("span",{pre:!0,attrs:{class:"token attr-value"}},[s("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),t._v("term"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])]),t._v(" "),s("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v("tag")]),s("span",{pre:!0,attrs:{class:"token attr-value"}},[s("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),t._v("label"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])]),t._v(" "),s("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v("for")]),s("span",{pre:!0,attrs:{class:"token attr-value"}},[s("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),t._v("tos"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("a")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v(":href")]),s("span",{pre:!0,attrs:{class:"token attr-value"}},[s("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),t._v("url"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])]),t._v(" "),s("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v("target")]),s("span",{pre:!0,attrs:{class:"token attr-value"}},[s("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),t._v("_blank"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("{{ $t('tos') }}"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token comment"}},[t._v("\x3c!-- ... --\x3e")]),t._v("\n"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n")])])]),s("div",{staticClass:"language-js extra-class"},[s("pre",{pre:!0,attrs:{class:"language-js"}},[s("code",[s("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("const")]),t._v(" messages "),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("en")]),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("tos")]),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token string"}},[t._v("'Term of Service'")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("term")]),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token string"}},[t._v("'I accept xxx {0}.'")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("ja")]),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("tos")]),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token string"}},[t._v("'利用規約'")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("term")]),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token string"}},[t._v("'私は xxx の{0}に同意します。'")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n\n"),s("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("const")]),t._v(" i18n "),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("new")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token class-name"}},[t._v("VueI18n")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("locale")]),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token string"}},[t._v("'en'")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n messages\n"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v("\n"),s("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("new")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token class-name"}},[t._v("Vue")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n i18n"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("data")]),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("url")]),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token string"}},[t._v("'/term'")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),s("span",{pre:!0,attrs:{class:"token function"}},[t._v("$mount")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),s("span",{pre:!0,attrs:{class:"token string"}},[t._v("'#app'")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v("\n")])])]),s("p",[t._v("the following output:")]),t._v(" "),s("div",{staticClass:"language-html extra-class"},[s("pre",{pre:!0,attrs:{class:"language-html"}},[s("code",[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("div")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v("id")]),s("span",{pre:!0,attrs:{class:"token attr-value"}},[s("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),t._v("app"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token comment"}},[t._v("\x3c!-- ... --\x3e")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("label")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v("for")]),s("span",{pre:!0,attrs:{class:"token attr-value"}},[s("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),t._v("tos"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("\n I accept xxx "),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("a")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v("href")]),s("span",{pre:!0,attrs:{class:"token attr-value"}},[s("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),t._v("/term"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])]),t._v(" "),s("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v("target")]),s("span",{pre:!0,attrs:{class:"token attr-value"}},[s("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),t._v("_blank"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("Term of Service"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v(".\n "),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token comment"}},[t._v("\x3c!-- ... --\x3e")]),t._v("\n"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n")])])]),s("p",[t._v("About the above example, see the "),s("a",{attrs:{href:"https://github.com/kazupon/vue-i18n/tree/dev/examples/interpolation/places",target:"_blank",rel:"noopener noreferrer"}},[t._v("example"),s("OutboundLink")],1)]),t._v(" "),s("p",[t._v("The children of "),s("code",[t._v("i18n")]),t._v(" functional component are interpolated with locale message of "),s("code",[t._v("path")]),t._v(" prop.")]),t._v(" "),s("p",[t._v("In the above example:")]),t._v(" "),s("div",{pre:!0},[s("p",[s("code",[t._v('{{ $t(\'tos\') }}')])])]),s("p",[t._v("is interpolated with "),s("code",[t._v("term")]),t._v(" locale message.")]),t._v(" "),s("p",[t._v("In the above example, the component interpolation follows the "),s("strong",[t._v("list formatting")]),t._v(". The children of "),s("code",[t._v("i18n")]),t._v(" functional component are interpolated by their order of appearance.")]),t._v(" "),s("p",[t._v("You can choose the root container's node type by specifying a "),s("code",[t._v("tag")]),t._v(" prop. If omitted, it defaults to "),s("code",[t._v("'span'")]),t._v(". You can also set it to the boolean value "),s("code",[t._v("false")]),t._v(" to insert the child nodes directly without creating a root element.")]),t._v(" "),s("h2",{attrs:{id:"slots-syntax-usage"}},[s("a",{staticClass:"header-anchor",attrs:{href:"#slots-syntax-usage"}},[t._v("#")]),t._v(" Slots syntax usage")]),t._v(" "),s("div",{staticClass:"custom-block tip"},[s("p",{staticClass:"custom-block-title"},[t._v("Support Version")]),t._v(" "),s("p",[t._v("🆕 8.14+")])]),t._v(" "),s("p",[t._v("It's more convenient to use the named slots syntax. For example:")]),t._v(" "),s("div",{staticClass:"language-html extra-class"},[s("pre",{pre:!0,attrs:{class:"language-html"}},[s("code",[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("div")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v("id")]),s("span",{pre:!0,attrs:{class:"token attr-value"}},[s("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),t._v("app"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token comment"}},[t._v("\x3c!-- ... --\x3e")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("i18n")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v("path")]),s("span",{pre:!0,attrs:{class:"token attr-value"}},[s("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),t._v("info"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])]),t._v(" "),s("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v("tag")]),s("span",{pre:!0,attrs:{class:"token attr-value"}},[s("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),t._v("p"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("template")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token attr-name"}},[s("span",{pre:!0,attrs:{class:"token namespace"}},[t._v("v-slot:")]),t._v("limit")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("span")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("{{ changeLimit }}"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("template")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token attr-name"}},[s("span",{pre:!0,attrs:{class:"token namespace"}},[t._v("v-slot:")]),t._v("action")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("a")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v(":href")]),s("span",{pre:!0,attrs:{class:"token attr-value"}},[s("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),t._v("changeUrl"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("{{ $t('change') }}"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token comment"}},[t._v("\x3c!-- ... --\x3e")]),t._v("\n"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n")])])]),s("div",{staticClass:"language-js extra-class"},[s("pre",{pre:!0,attrs:{class:"language-js"}},[s("code",[s("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("const")]),t._v(" messages "),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("en")]),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("info")]),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token string"}},[t._v("'You can {action} until {limit} minutes from departure.'")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("change")]),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token string"}},[t._v("'change your flight'")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("refund")]),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token string"}},[t._v("'refund the ticket'")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n\n"),s("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("const")]),t._v(" i18n "),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("new")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token class-name"}},[t._v("VueI18n")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("locale")]),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token string"}},[t._v("'en'")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n messages\n"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v("\n\n"),s("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("new")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token class-name"}},[t._v("Vue")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n i18n"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("data")]),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("changeUrl")]),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token string"}},[t._v("'/change'")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("refundUrl")]),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token string"}},[t._v("'/refund'")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("changeLimit")]),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token number"}},[t._v("15")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("refundLimit")]),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token number"}},[t._v("30")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),s("span",{pre:!0,attrs:{class:"token function"}},[t._v("$mount")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),s("span",{pre:!0,attrs:{class:"token string"}},[t._v("'#app'")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v("\n")])])]),s("p",[t._v("Outputs:")]),t._v(" "),s("div",{staticClass:"language-html extra-class"},[s("pre",{pre:!0,attrs:{class:"language-html"}},[s("code",[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("div")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v("id")]),s("span",{pre:!0,attrs:{class:"token attr-value"}},[s("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),t._v("app"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token comment"}},[t._v("\x3c!-- ... --\x3e")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("p")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("\n You can "),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("a")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v("href")]),s("span",{pre:!0,attrs:{class:"token attr-value"}},[s("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),t._v("/change"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("change your flight"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v(" until "),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("span")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("15"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v(" minutes from departure.\n "),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token comment"}},[t._v("\x3c!-- ... --\x3e")]),t._v("\n"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n")])])]),s("p",[t._v("In Vue 2.6 and later, you can use the following slots syntax in templates:")]),t._v(" "),s("div",{staticClass:"language-html extra-class"},[s("pre",{pre:!0,attrs:{class:"language-html"}},[s("code",[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("div")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v("id")]),s("span",{pre:!0,attrs:{class:"token attr-value"}},[s("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),t._v("app"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token comment"}},[t._v("\x3c!-- ... --\x3e")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("i18n")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v("path")]),s("span",{pre:!0,attrs:{class:"token attr-value"}},[s("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),t._v("info"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])]),t._v(" "),s("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v("tag")]),s("span",{pre:!0,attrs:{class:"token attr-value"}},[s("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),t._v("p"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("template")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v("#limit")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("span")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("{{ changeLimit }}"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("template")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v("#action")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("a")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v(":href")]),s("span",{pre:!0,attrs:{class:"token attr-value"}},[s("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),t._v("changeUrl"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("{{ $t('change') }}"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token comment"}},[t._v("\x3c!-- ... --\x3e")]),t._v("\n"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n")])])]),s("div",{staticClass:"custom-block warning"},[s("p",{staticClass:"custom-block-title"},[t._v("Limitation")]),t._v(" "),s("p",[t._v("⚠️ In "),s("code",[t._v("i18n")]),t._v(" component, slots props are not supported.")])]),t._v(" "),s("h2",{attrs:{id:"places-syntax-usage"}},[s("a",{staticClass:"header-anchor",attrs:{href:"#places-syntax-usage"}},[t._v("#")]),t._v(" Places syntax usage")]),t._v(" "),s("div",{staticClass:"custom-block danger"},[s("p",{staticClass:"custom-block-title"},[t._v("Important!!")]),t._v(" "),s("p",[t._v("In the next major version, the "),s("code",[t._v("place")]),t._v(" and "),s("code",[t._v("places")]),t._v(" props will be deprecated. Please switch to slots syntax.")])]),t._v(" "),s("div",{staticClass:"custom-block tip"},[s("p",{staticClass:"custom-block-title"},[t._v("Support Version")]),t._v(" "),s("p",[t._v("🆕 7.2+")])]),t._v(" "),s("div",{staticClass:"custom-block warning"},[s("p",{staticClass:"custom-block-title"},[t._v("Notice")]),t._v(" "),s("p",[t._v("⚠️ In "),s("code",[t._v("i18n")]),t._v(" component, text content consisting of only white spaces will be omitted.")])]),t._v(" "),s("p",[t._v("Named formatting is supported with the help of "),s("code",[t._v("place")]),t._v(" attribute. For example:")]),t._v(" "),s("div",{staticClass:"language-html extra-class"},[s("pre",{pre:!0,attrs:{class:"language-html"}},[s("code",[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("div")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v("id")]),s("span",{pre:!0,attrs:{class:"token attr-value"}},[s("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),t._v("app"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token comment"}},[t._v("\x3c!-- ... --\x3e")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("i18n")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v("path")]),s("span",{pre:!0,attrs:{class:"token attr-value"}},[s("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),t._v("info"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])]),t._v(" "),s("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v("tag")]),s("span",{pre:!0,attrs:{class:"token attr-value"}},[s("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),t._v("p"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("span")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v("place")]),s("span",{pre:!0,attrs:{class:"token attr-value"}},[s("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),t._v("limit"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("{{ changeLimit }}"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("a")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v("place")]),s("span",{pre:!0,attrs:{class:"token attr-value"}},[s("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),t._v("action"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])]),t._v(" "),s("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v(":href")]),s("span",{pre:!0,attrs:{class:"token attr-value"}},[s("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),t._v("changeUrl"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("{{ $t('change') }}"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token comment"}},[t._v("\x3c!-- ... --\x3e")]),t._v("\n"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n")])])]),s("div",{staticClass:"language-js extra-class"},[s("pre",{pre:!0,attrs:{class:"language-js"}},[s("code",[s("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("const")]),t._v(" messages "),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("en")]),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("info")]),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token string"}},[t._v("'You can {action} until {limit} minutes from departure.'")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("change")]),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token string"}},[t._v("'change your flight'")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("refund")]),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token string"}},[t._v("'refund the ticket'")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n\n"),s("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("const")]),t._v(" i18n "),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("new")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token class-name"}},[t._v("VueI18n")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("locale")]),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token string"}},[t._v("'en'")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n messages\n"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v("\n"),s("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("new")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token class-name"}},[t._v("Vue")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n i18n"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("data")]),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("changeUrl")]),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token string"}},[t._v("'/change'")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("refundUrl")]),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token string"}},[t._v("'/refund'")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("changeLimit")]),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token number"}},[t._v("15")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("refundLimit")]),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token number"}},[t._v("30")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),s("span",{pre:!0,attrs:{class:"token function"}},[t._v("$mount")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),s("span",{pre:!0,attrs:{class:"token string"}},[t._v("'#app'")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v("\n")])])]),s("p",[t._v("Outputs:")]),t._v(" "),s("div",{staticClass:"language-html extra-class"},[s("pre",{pre:!0,attrs:{class:"language-html"}},[s("code",[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("div")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v("id")]),s("span",{pre:!0,attrs:{class:"token attr-value"}},[s("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),t._v("app"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token comment"}},[t._v("\x3c!-- ... --\x3e")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("p")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("\n You can "),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("a")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v("href")]),s("span",{pre:!0,attrs:{class:"token attr-value"}},[s("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),t._v("/change"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("change your flight"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v(" until "),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("span")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("15"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v(" minutes from departure.\n "),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token comment"}},[t._v("\x3c!-- ... --\x3e")]),t._v("\n"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n")])])]),s("div",{staticClass:"custom-block warning"},[s("p",{staticClass:"custom-block-title"},[t._v("Notice")]),t._v(" "),s("p",[t._v("⚠️ To use named formatting, all children of "),s("code",[t._v("i18n")]),t._v(" component must have "),s("code",[t._v("place")]),t._v(" attribute set. Otherwise it will fallback to list formatting.")])]),t._v(" "),s("p",[t._v("If you still want to interpolate text content in named formatting, you could define "),s("code",[t._v("places")]),t._v(" property on "),s("code",[t._v("i18n")]),t._v(" component. For example:")]),t._v(" "),s("div",{staticClass:"language-html extra-class"},[s("pre",{pre:!0,attrs:{class:"language-html"}},[s("code",[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("div")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v("id")]),s("span",{pre:!0,attrs:{class:"token attr-value"}},[s("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),t._v("app"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token comment"}},[t._v("\x3c!-- ... --\x3e")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("i18n")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v("path")]),s("span",{pre:!0,attrs:{class:"token attr-value"}},[s("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),t._v("info"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])]),t._v(" "),s("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v("tag")]),s("span",{pre:!0,attrs:{class:"token attr-value"}},[s("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),t._v("p"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])]),t._v(" "),s("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v(":places")]),s("span",{pre:!0,attrs:{class:"token attr-value"}},[s("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),t._v("{ limit: refundLimit }"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("a")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v("place")]),s("span",{pre:!0,attrs:{class:"token attr-value"}},[s("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),t._v("action"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])]),t._v(" "),s("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v(":href")]),s("span",{pre:!0,attrs:{class:"token attr-value"}},[s("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),t._v("refundUrl"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("{{ $t('refund') }}"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token comment"}},[t._v("\x3c!-- ... --\x3e")]),t._v("\n"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n")])])]),s("p",[t._v("Outputs:")]),t._v(" "),s("div",{staticClass:"language-html extra-class"},[s("pre",{pre:!0,attrs:{class:"language-html"}},[s("code",[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("div")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v("id")]),s("span",{pre:!0,attrs:{class:"token attr-value"}},[s("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),t._v("app"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token comment"}},[t._v("\x3c!-- ... --\x3e")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("p")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("\n You can "),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("a")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v("href")]),s("span",{pre:!0,attrs:{class:"token attr-value"}},[s("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),t._v("/refund"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("refund your ticket"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v(" until 30 minutes from departure.\n "),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token comment"}},[t._v("\x3c!-- ... --\x3e")]),t._v("\n"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n")])])])])}),[],!1,null,null,null);a.default=e.exports}}]); \ No newline at end of file diff --git a/assets/js/18.71d9fded.js b/assets/js/18.71d9fded.js new file mode 100644 index 000000000..647128219 --- /dev/null +++ b/assets/js/18.71d9fded.js @@ -0,0 +1 @@ +(window.webpackJsonp=window.webpackJsonp||[]).push([[18],{469:function(t,s,a){"use strict";a.r(s);var n=a(44),e=Object(n.a)({},(function(){var t=this,s=t.$createElement,a=t._self._c||s;return a("ContentSlotsDistributor",{attrs:{"slot-key":t.$parent.slotKey}},[a("h1",{attrs:{id:"lazy-loading-translations"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#lazy-loading-translations"}},[t._v("#")]),t._v(" Lazy loading translations")]),t._v(" "),a("p",[t._v("Loading all of your translation files at once is overkill and unnecessary.")]),t._v(" "),a("p",[t._v("Lazy loading or asynchronously loading the translation files is really easy when using Webpack.")]),t._v(" "),a("p",[t._v("Let´s assume we have a project directory similar to the one below:")]),t._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[t._v("our-cool-project\n-dist\n-src\n--routes\n--store\n--setup\n---i18n-setup.js\n--lang\n---en.js\n---it.js\n")])])]),a("p",[t._v("The "),a("code",[t._v("lang")]),t._v(" folder is where all of our translation files reside. The "),a("code",[t._v("setup")]),t._v(" folder is where our arbitrary setup files like the i18n-setup, global component inits, plugin inits and other reside.")]),t._v(" "),a("div",{staticClass:"language-js extra-class"},[a("pre",{pre:!0,attrs:{class:"language-js"}},[a("code",[a("span",{pre:!0,attrs:{class:"token comment"}},[t._v("//i18n-setup.js")]),t._v("\n"),a("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("import")]),t._v(" Vue "),a("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("from")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v("'vue'")]),t._v("\n"),a("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("import")]),t._v(" VueI18n "),a("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("from")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v("'vue-i18n'")]),t._v("\n"),a("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("import")]),t._v(" messages "),a("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("from")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v("'@/lang/en'")]),t._v("\n"),a("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("import")]),t._v(" axios "),a("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("from")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v("'axios'")]),t._v("\n\nVue"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),a("span",{pre:!0,attrs:{class:"token function"}},[t._v("use")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v("VueI18n"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v("\n\n"),a("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("export")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("const")]),t._v(" i18n "),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("new")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token class-name"}},[t._v("VueI18n")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("locale")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v("'en'")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// set locale")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("fallbackLocale")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v("'en'")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n messages "),a("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// set locale messages")]),t._v("\n"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v("\n\n"),a("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("const")]),t._v(" loadedLanguages "),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("[")]),a("span",{pre:!0,attrs:{class:"token string"}},[t._v("'en'")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("]")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// our default language that is preloaded")]),t._v("\n\n"),a("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("function")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token function"}},[t._v("setI18nLanguage")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),a("span",{pre:!0,attrs:{class:"token parameter"}},[t._v("lang")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n i18n"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("locale "),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" lang\n axios"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("defaults"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("headers"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("common"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("[")]),a("span",{pre:!0,attrs:{class:"token string"}},[t._v("'Accept-Language'")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("]")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" lang\n document"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),a("span",{pre:!0,attrs:{class:"token function"}},[t._v("querySelector")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),a("span",{pre:!0,attrs:{class:"token string"}},[t._v("'html'")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),a("span",{pre:!0,attrs:{class:"token function"}},[t._v("setAttribute")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),a("span",{pre:!0,attrs:{class:"token string"}},[t._v("'lang'")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" lang"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("return")]),t._v(" lang\n"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n\n"),a("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("export")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("function")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token function"}},[t._v("loadLanguageAsync")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),a("span",{pre:!0,attrs:{class:"token parameter"}},[t._v("lang")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// If the same language")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("if")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v("i18n"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("locale "),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v("===")]),t._v(" lang"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("return")]),t._v(" Promise"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),a("span",{pre:!0,attrs:{class:"token function"}},[t._v("resolve")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),a("span",{pre:!0,attrs:{class:"token function"}},[t._v("setI18nLanguage")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v("lang"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n\n "),a("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// If the language was already loaded")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("if")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v("loadedLanguages"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),a("span",{pre:!0,attrs:{class:"token function"}},[t._v("includes")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v("lang"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("return")]),t._v(" Promise"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),a("span",{pre:!0,attrs:{class:"token function"}},[t._v("resolve")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),a("span",{pre:!0,attrs:{class:"token function"}},[t._v("setI18nLanguage")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v("lang"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n\n "),a("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// If the language hasn't been loaded yet")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("return")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("import")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),a("span",{pre:!0,attrs:{class:"token comment"}},[t._v('/* webpackChunkName: "lang-[request]" */')]),t._v(" "),a("span",{pre:!0,attrs:{class:"token template-string"}},[a("span",{pre:!0,attrs:{class:"token template-punctuation string"}},[t._v("`")]),a("span",{pre:!0,attrs:{class:"token string"}},[t._v("@/lang/")]),a("span",{pre:!0,attrs:{class:"token interpolation"}},[a("span",{pre:!0,attrs:{class:"token interpolation-punctuation punctuation"}},[t._v("${")]),t._v("lang"),a("span",{pre:!0,attrs:{class:"token interpolation-punctuation punctuation"}},[t._v("}")])]),a("span",{pre:!0,attrs:{class:"token string"}},[t._v(".js")]),a("span",{pre:!0,attrs:{class:"token template-punctuation string"}},[t._v("`")])]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),a("span",{pre:!0,attrs:{class:"token function"}},[t._v("then")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token parameter"}},[t._v("messages")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=>")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n i18n"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),a("span",{pre:!0,attrs:{class:"token function"}},[t._v("setLocaleMessage")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v("lang"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" messages"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("default"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v("\n loadedLanguages"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),a("span",{pre:!0,attrs:{class:"token function"}},[t._v("push")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v("lang"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("return")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token function"}},[t._v("setI18nLanguage")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v("lang"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v("\n"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n")])])]),a("p",[t._v("In short we are creating a new VueI18n instance as we normally would. Then we are creating a "),a("code",[t._v("loadedLanguages")]),t._v(" array that will keep track of our loaded languages. Next is the "),a("code",[t._v("setI18nLanguage")]),t._v(" function that will actually change the language in our vueI18n instance, axios and where ever else is needed.")]),t._v(" "),a("p",[t._v("The "),a("code",[t._v("loadLanguageAsync")]),t._v(" function is what we will actually use to change the languages. Loading the new files is done via the "),a("code",[t._v("import")]),t._v(" function, which is generously provided by Webpack and it allows us to load files dynamically, and because it uses promises we can easily wait for the loading to finish.")]),t._v(" "),a("p",[t._v("You can learn more about the import function in the "),a("a",{attrs:{href:"https://webpack.js.org/guides/code-splitting/#dynamic-imports",target:"_blank",rel:"noopener noreferrer"}},[t._v("Webpack documentation"),a("OutboundLink")],1),t._v(".")]),t._v(" "),a("p",[t._v("Using the "),a("code",[t._v("loadLanguageAsync")]),t._v(" function is straightforward. A common use case is inside a vue-router beforeEach hook.")]),t._v(" "),a("div",{staticClass:"language-js extra-class"},[a("pre",{pre:!0,attrs:{class:"language-js"}},[a("code",[t._v("router"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),a("span",{pre:!0,attrs:{class:"token function"}},[t._v("beforeEach")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),a("span",{pre:!0,attrs:{class:"token parameter"}},[t._v("to"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" from"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" next")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=>")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("const")]),t._v(" lang "),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" to"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("params"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("lang\n "),a("span",{pre:!0,attrs:{class:"token function"}},[t._v("loadLanguageAsync")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v("lang"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),a("span",{pre:!0,attrs:{class:"token function"}},[t._v("then")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=>")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token function"}},[t._v("next")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v("\n"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v("\n")])])]),a("p",[t._v("We could improve this by checking if the "),a("code",[t._v("lang")]),t._v(" is actually supported by us or not, call "),a("code",[t._v("reject")]),t._v(" so we can catch that in the "),a("code",[t._v("beforeEach")]),t._v(" stopping the route transition.")])])}),[],!1,null,null,null);s.default=e.exports}}]); \ No newline at end of file diff --git a/assets/js/19.f25e213e.js b/assets/js/19.f25e213e.js new file mode 100644 index 000000000..8fb9f2539 --- /dev/null +++ b/assets/js/19.f25e213e.js @@ -0,0 +1 @@ +(window.webpackJsonp=window.webpackJsonp||[]).push([[19],{468:function(t,a,s){"use strict";s.r(a);var n=s(44),e=Object(n.a)({},(function(){var t=this,a=t.$createElement,s=t._self._c||a;return s("ContentSlotsDistributor",{attrs:{"slot-key":t.$parent.slotKey}},[s("h1",{attrs:{id:"locale-changing"}},[s("a",{staticClass:"header-anchor",attrs:{href:"#locale-changing"}},[t._v("#")]),t._v(" Locale changing")]),t._v(" "),s("p",[t._v("Normally, using the root Vue instance as the starting point, all child components are localized using the "),s("code",[t._v("locale")]),t._v(" property of the "),s("code",[t._v("VueI18n")]),t._v(" class as a reference.")]),t._v(" "),s("p",[t._v("Sometimes you might want to dynamically change the locale. In that case you can change the value of the "),s("code",[t._v("locale")]),t._v(" property of the "),s("code",[t._v("VueI18n")]),t._v(" instance.")]),t._v(" "),s("div",{staticClass:"language-js extra-class"},[s("pre",{pre:!0,attrs:{class:"language-js"}},[s("code",[s("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("const")]),t._v(" i18n "),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("new")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token class-name"}},[t._v("VueI18n")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("locale")]),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token string"}},[t._v("'ja'")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// set locale")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v("...")]),t._v("\n"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v("\n\n"),s("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// create root Vue instance")]),t._v("\n"),s("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("new")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token class-name"}},[t._v("Vue")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n i18n"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v("...")]),t._v("\n"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),s("span",{pre:!0,attrs:{class:"token function"}},[t._v("$mount")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),s("span",{pre:!0,attrs:{class:"token string"}},[t._v("'#app'")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v("\n\n"),s("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// change other locale")]),t._v("\ni18n"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("locale "),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token string"}},[t._v("'en'")]),t._v("\n")])])]),s("p",[t._v("Each component contains a "),s("code",[t._v("VueI18n")]),t._v(" instance referenced as the "),s("code",[t._v("$i18n")]),t._v(" property that can also be used to change the locale.")]),t._v(" "),s("p",[t._v("Example:")]),t._v(" "),s("div",{staticClass:"language-vue extra-class"},[s("pre",{pre:!0,attrs:{class:"language-vue"}},[s("code",[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("template")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("div")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v("class")]),s("span",{pre:!0,attrs:{class:"token attr-value"}},[s("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),t._v("locale-changer"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("select")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v("v-model")]),s("span",{pre:!0,attrs:{class:"token attr-value"}},[s("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),t._v("$i18n.locale"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("option")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v("v-for")]),s("span",{pre:!0,attrs:{class:"token attr-value"}},[s("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),t._v("(lang, i) in langs"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])]),t._v(" "),s("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v(":key")]),s("span",{pre:!0,attrs:{class:"token attr-value"}},[s("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),t._v("`Lang${i}`"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])]),t._v(" "),s("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v(":value")]),s("span",{pre:!0,attrs:{class:"token attr-value"}},[s("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),t._v("lang"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("\n {{ lang }}\n "),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n\n"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("script")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),s("span",{pre:!0,attrs:{class:"token script"}},[s("span",{pre:!0,attrs:{class:"token language-javascript"}},[t._v("\n"),s("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("export")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("default")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("name")]),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token string"}},[t._v("'locale-changer'")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token function"}},[t._v("data")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("return")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("langs")]),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("[")]),s("span",{pre:!0,attrs:{class:"token string"}},[t._v("'ja'")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token string"}},[t._v("'en'")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("]")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n")])]),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n")])])]),s("div",{staticClass:"custom-block warning"},[s("p",{staticClass:"custom-block-title"},[t._v("Notice")]),t._v(" "),s("p",[t._v("⚠️ Locale changing is ignored for components that use "),s("code",[t._v("sync: false")]),t._v(".")])]),t._v(" "),s("div",{staticClass:"custom-block warning"},[s("p",{staticClass:"custom-block-title"},[t._v("Component vs. root scope")]),t._v(" "),s("p",[t._v("⚠️ Changing "),s("code",[t._v("$i18n.locale")]),t._v(" inside a component does not update the root locale.\nIf you rely on the root locale, for example when using "),s("RouterLink",{attrs:{to:"/guide/fallback.html"}},[t._v("root fallbacks")]),t._v(", use "),s("code",[t._v("$root.$i18n.locale")]),t._v(" instead of "),s("code",[t._v("$i18n.locale")]),t._v(".")],1)])])}),[],!1,null,null,null);a.default=e.exports}}]); \ No newline at end of file diff --git a/assets/js/2.6307267c.js b/assets/js/2.6307267c.js new file mode 100644 index 000000000..b188ebd08 --- /dev/null +++ b/assets/js/2.6307267c.js @@ -0,0 +1 @@ +(window.webpackJsonp=window.webpackJsonp||[]).push([[2],{314:function(t,e,n){"use strict";n.d(e,"d",(function(){return i})),n.d(e,"a",(function(){return a})),n.d(e,"i",(function(){return s})),n.d(e,"f",(function(){return u})),n.d(e,"g",(function(){return l})),n.d(e,"h",(function(){return c})),n.d(e,"b",(function(){return h})),n.d(e,"e",(function(){return f})),n.d(e,"k",(function(){return p})),n.d(e,"l",(function(){return d})),n.d(e,"c",(function(){return v})),n.d(e,"j",(function(){return m}));n(29),n(99),n(169),n(102),n(176),n(71),n(45),n(316),n(72),n(336),n(101);var i=/#.*$/,r=/\.(md|html)$/,a=/\/$/,s=/^[a-z]+:/i;function o(t){return decodeURI(t).replace(i,"").replace(r,"")}function u(t){return s.test(t)}function l(t){return/^mailto:/.test(t)}function c(t){return/^tel:/.test(t)}function h(t){if(u(t))return t;var e=t.match(i),n=e?e[0]:"",r=o(t);return a.test(r)?t:r+".html"+n}function f(t,e){var n=decodeURIComponent(t.hash),r=function(t){var e=t.match(i);if(e)return e[0]}(e);return(!r||n===r)&&o(t.path)===o(e)}function p(t,e,n){if(u(e))return{type:"external",path:e};n&&(e=function(t,e,n){var i=t.charAt(0);if("/"===i)return t;if("?"===i||"#"===i)return e+t;var r=e.split("/");n&&r[r.length-1]||r.pop();for(var a=t.replace(/^\//,"").split("/"),s=0;s3&&void 0!==arguments[3]?arguments[3]:1;if("string"==typeof e)return p(n,e,i);if(Array.isArray(e))return Object.assign(p(n,e[0],i),{title:e[1]});var a=e.children||[];return 0===a.length&&e.path?Object.assign(p(n,e.path,i),{title:e.title}):{type:"group",path:e.path,title:e.title,sidebarDepth:e.sidebarDepth,initialOpenGroupIndex:e.initialOpenGroupIndex,children:a.map((function(e){return t(e,n,i,r+1)})),collapsable:!1!==e.collapsable}}(t,r,l)})):[]}return[]}function g(t){var e=v(t.headers||[]);return[{type:"group",collapsable:!1,title:t.title,path:null,children:e.map((function(e){return{type:"auto",title:e.title,basePath:t.path,path:t.path+"#"+e.slug,children:e.children||[]}}))}]}function v(t){var e;return(t=t.map((function(t){return Object.assign({},t)}))).forEach((function(t){2===t.level?e=t:e&&(e.children||(e.children=[])).push(t)})),t.filter((function(t){return 2===t.level}))}function m(t){return Object.assign(t,{type:t.items&&t.items.length?"links":"link"})}},316:function(t,e,n){"use strict";var i=n(172),r=n(5),a=n(12),s=n(18),o=n(22),u=n(173),l=n(174);i("match",(function(t,e,n){return[function(e){var n=o(this),i=null==e?void 0:e[t];return void 0!==i?i.call(e,n):new RegExp(e)[t](s(n))},function(t){var i=r(this),o=s(t),c=n(e,i,o);if(c.done)return c.value;if(!i.global)return l(i,o);var h=i.unicode;i.lastIndex=0;for(var f,p=[],d=0;null!==(f=l(i,o));){var g=s(f[0]);p[d]=g,""===g&&(i.lastIndex=u(o,a(i.lastIndex),h)),d++}return 0===d?null:p}]}))},317:function(t,e,n){},318:function(t,e){t.exports="\t\n\v\f\r                 \u2028\u2029\ufeff"},319:function(t,e,n){},320:function(t,e,n){},321:function(t,e,n){},322:function(t,e,n){},323:function(t,e,n){},324:function(t,e,n){},325:function(t,e,n){},326:function(t,e,n){},327:function(t,e,n){},328:function(t,e,n){},329:function(t,e,n){},330:function(t,e,n){},336:function(t,e,n){"use strict";var i=n(172),r=n(170),a=n(5),s=n(22),o=n(106),u=n(173),l=n(12),c=n(18),h=n(174),f=n(74),p=n(171),d=n(1),g=p.UNSUPPORTED_Y,v=[].push,m=Math.min;i("split",(function(t,e,n){var i;return i="c"=="abbc".split(/(b)*/)[1]||4!="test".split(/(?:)/,-1).length||2!="ab".split(/(?:ab)*/).length||4!=".".split(/(.?)(.?)/).length||".".split(/()()/).length>1||"".split(/.?/).length?function(t,n){var i=c(s(this)),a=void 0===n?4294967295:n>>>0;if(0===a)return[];if(void 0===t)return[i];if(!r(t))return e.call(i,t,a);for(var o,u,l,h=[],p=(t.ignoreCase?"i":"")+(t.multiline?"m":"")+(t.unicode?"u":"")+(t.sticky?"y":""),d=0,g=new RegExp(t.source,p+"g");(o=f.call(g,i))&&!((u=g.lastIndex)>d&&(h.push(i.slice(d,o.index)),o.length>1&&o.index=a));)g.lastIndex===o.index&&g.lastIndex++;return d===i.length?!l&&g.test("")||h.push(""):h.push(i.slice(d)),h.length>a?h.slice(0,a):h}:"0".split(void 0,0).length?function(t,n){return void 0===t&&0===n?[]:e.call(this,t,n)}:e,[function(e,n){var r=s(this),a=null==e?void 0:e[t];return void 0!==a?a.call(e,r,n):i.call(c(r),e,n)},function(t,r){var s=a(this),f=c(t),p=n(i,s,f,r,i!==e);if(p.done)return p.value;var d=o(s,RegExp),v=s.unicode,b=(s.ignoreCase?"i":"")+(s.multiline?"m":"")+(s.unicode?"u":"")+(g?"g":"y"),k=new d(g?"^(?:"+s.source+")":s,b),_=void 0===r?4294967295:r>>>0;if(0===_)return[];if(0===f.length)return null===h(k,f)?[f]:[];for(var x=0,C=0,y=[];C@^][^\s!#%&*+<=>@^]*>/,w=/a/g,O=/a/g,S=new y(w)!==w,I=p.UNSUPPORTED_Y,E=i&&(!S||I||_||x||g((function(){return O[C]=!1,y(w)!=w||y(O)==O||"/a/i"!=y(w,"i")})));if(a("RegExp",E)){for(var j=function(t,e){var n,i,r,a,u,l,p=this instanceof j,d=c(t),g=void 0===e,b=[],k=t;if(!p&&d&&g&&t.constructor===j)return t;if((d||t instanceof j)&&(t=t.source,g&&(e="flags"in k?k.flags:f.call(k))),t=void 0===t?"":h(t),e=void 0===e?"":h(e),k=t,_&&"dotAll"in w&&(i=!!e&&e.indexOf("s")>-1)&&(e=e.replace(/s/g,"")),n=e,I&&"sticky"in w&&(r=!!e&&e.indexOf("y")>-1)&&(e=e.replace(/y/g,"")),x&&(t=(a=function(t){for(var e,n=t.length,i=0,r="",a=[],s={},o=!1,u=!1,l=0,c="";i<=n;i++){if("\\"===(e=t.charAt(i)))e+=t.charAt(++i);else if("]"===e)o=!1;else if(!o)switch(!0){case"["===e:o=!0;break;case"("===e:L.test(t.slice(i+1))&&(i+=2,u=!0),r+=e,l++;continue;case">"===e&&u:if(""===c||v(s,c))throw new SyntaxError("Invalid capture group name");s[c]=!0,a.push([c,l]),u=!1,c="";continue}u?c+=e:r+=e}return[r,a]}(t))[0],b=a[1]),u=s(y(t,e),p?this:$,j),(i||r||b.length)&&(l=m(u),i&&(l.dotAll=!0,l.raw=j(function(t){for(var e,n=t.length,i=0,r="",a=!1;i<=n;i++)"\\"!==(e=t.charAt(i))?a||"."!==e?("["===e?a=!0:"]"===e&&(a=!1),r+=e):r+="[\\s\\S]":r+=e+t.charAt(++i);return r}(t),n)),r&&(l.sticky=!0),b.length&&(l.groups=b)),t!==k)try{o(u,"source",""===k?"(?:)":k)}catch(t){}return u},A=function(t){t in j||u(j,t,{configurable:!0,get:function(){return y[t]},set:function(e){y[t]=e}})},N=l(y),T=0;N.length>T;)A(N[T++]);$.constructor=j,j.prototype=$,d(r,"RegExp",j)}b("RegExp")},340:function(t,e){t.exports=function(t){return null==t}},341:function(t,e,n){"use strict";n.r(e);n(98);var i=n(314),r={name:"SidebarGroup",components:{DropdownTransition:n(342).a},props:["item","open","collapsable","depth"],beforeCreate:function(){this.$options.components.SidebarLinks=n(341).default},methods:{isActive:i.e}},a=(n(363),n(44)),s=Object(a.a)(r,(function(){var t=this,e=t.$createElement,n=t._self._c||e;return n("section",{staticClass:"sidebar-group",class:[{collapsable:t.collapsable,"is-sub-group":0!==t.depth},"depth-"+t.depth]},[t.item.path?n("RouterLink",{staticClass:"sidebar-heading clickable",class:{open:t.open,active:t.isActive(t.$route,t.item.path)},attrs:{to:t.item.path},nativeOn:{click:function(e){return t.$emit("toggle")}}},[n("span",[t._v(t._s(t.item.title))]),t._v(" "),t.collapsable?n("span",{staticClass:"arrow",class:t.open?"down":"right"}):t._e()]):n("p",{staticClass:"sidebar-heading",class:{open:t.open},on:{click:function(e){return t.$emit("toggle")}}},[n("span",[t._v(t._s(t.item.title))]),t._v(" "),t.collapsable?n("span",{staticClass:"arrow",class:t.open?"down":"right"}):t._e()]),t._v(" "),n("DropdownTransition",[t.open||!t.collapsable?n("SidebarLinks",{staticClass:"sidebar-group-items",attrs:{items:t.item.children,"sidebar-depth":t.item.sidebarDepth,"initial-open-group-index":t.item.initialOpenGroupIndex,depth:t.depth+1}}):t._e()],1)],1)}),[],!1,null,null,null).exports;n(364),n(71);function o(t,e,n,i,r){var a={props:{to:e,activeClass:"",exactActiveClass:""},class:{active:i,"sidebar-link":!0}};return r>2&&(a.style={"padding-left":r+"rem"}),t("RouterLink",a,n)}function u(t,e,n,r,a){var s=arguments.length>5&&void 0!==arguments[5]?arguments[5]:1;return!e||s>a?null:t("ul",{class:"sidebar-sub-headers"},e.map((function(e){var l=Object(i.e)(r,n+"#"+e.slug);return t("li",{class:"sidebar-sub-header"},[o(t,n+"#"+e.slug,e.title,l,e.level-1),u(t,e.children,n,r,a,s+1)])})))}var l={functional:!0,props:["item","sidebarDepth"],render:function(t,e){var n=e.parent,r=n.$page,a=(n.$site,n.$route),s=n.$themeConfig,l=n.$themeLocaleConfig,c=e.props,h=c.item,f=c.sidebarDepth,p=Object(i.e)(a,h.path),d="auto"===h.type?p||h.children.some((function(t){return Object(i.e)(a,h.basePath+"#"+t.slug)})):p,g="external"===h.type?function(t,e,n){return t("a",{attrs:{href:e,target:"_blank",rel:"noopener noreferrer"},class:{"sidebar-link":!0}},[n,t("OutboundLink")])}(t,h.path,h.title||h.path):o(t,h.path,h.title||h.path,d),v=[r.frontmatter.sidebarDepth,f,l.sidebarDepth,s.sidebarDepth,1].find((function(t){return void 0!==t})),m=l.displayAllHeaders||s.displayAllHeaders;return"auto"===h.type?[g,u(t,h.children,h.basePath,a,v)]:(d||m)&&h.headers&&!i.d.test(h.path)?[g,u(t,Object(i.c)(h.headers),h.path,a,v)]:g}};n(365);function c(t,e){if("group"===e.type){var n=e.path&&Object(i.e)(t,e.path),r=e.children.some((function(e){return"group"===e.type?c(t,e):"page"===e.type&&Object(i.e)(t,e.path)}));return n||r}return!1}var h={name:"SidebarLinks",components:{SidebarGroup:s,SidebarLink:Object(a.a)(l,void 0,void 0,!1,null,null,null).exports},props:["items","depth","sidebarDepth","initialOpenGroupIndex"],data:function(){return{openGroupIndex:this.initialOpenGroupIndex||0}},watch:{$route:function(){this.refreshIndex()}},created:function(){this.refreshIndex()},methods:{refreshIndex:function(){var t=function(t,e){for(var n=0;n-1&&(this.openGroupIndex=t)},toggleGroup:function(t){this.openGroupIndex=t===this.openGroupIndex?-1:t},isActive:function(t){return Object(i.e)(this.$route,t.regularPath)}}},f=Object(a.a)(h,(function(){var t=this,e=t.$createElement,n=t._self._c||e;return t.items.length?n("ul",{staticClass:"sidebar-links"},t._l(t.items,(function(e,i){return n("li",{key:i},["group"===e.type?n("SidebarGroup",{attrs:{item:e,open:i===t.openGroupIndex,collapsable:e.collapsable||e.collapsible,depth:t.depth},on:{toggle:function(e){return t.toggleGroup(i)}}}):n("SidebarLink",{attrs:{"sidebar-depth":t.sidebarDepth,item:e}})],1)})),0):t._e()}),[],!1,null,null,null);e.default=f.exports},342:function(t,e,n){"use strict";var i={name:"DropdownTransition",methods:{setHeight:function(t){t.style.height=t.scrollHeight+"px"},unsetHeight:function(t){t.style.height=""}}},r=(n(355),n(44)),a=Object(r.a)(i,(function(){var t=this.$createElement;return(this._self._c||t)("transition",{attrs:{name:"dropdown"},on:{enter:this.setHeight,"after-enter":this.unsetHeight,"before-leave":this.setHeight}},[this._t("default")],2)}),[],!1,null,null,null);e.a=a.exports},344:function(t,e,n){"use strict";var i=n(0),r=n(345);i({target:"String",proto:!0,forced:n(346)("link")},{link:function(t){return r(this,"a","href",t)}})},345:function(t,e,n){var i=n(22),r=n(18),a=/"/g;t.exports=function(t,e,n,s){var o=r(i(t)),u="<"+e;return""!==n&&(u+=" "+n+'="'+r(s).replace(a,""")+'"'),u+">"+o+""}},346:function(t,e,n){var i=n(1);t.exports=function(t){return i((function(){var e=""[t]('"');return e!==e.toLowerCase()||e.split('"').length>3}))}},347:function(t,e,n){"use strict";var i=n(317);n.n(i).a},348:function(t,e,n){var i=n(0),r=n(349);i({global:!0,forced:parseInt!=r},{parseInt:r})},349:function(t,e,n){var i=n(3),r=n(18),a=n(337).trim,s=n(318),o=i.parseInt,u=/^[+-]?0[Xx]/,l=8!==o(s+"08")||22!==o(s+"0x16");t.exports=l?function(t,e){var n=a(r(t));return o(n,e>>>0||(u.test(n)?16:10))}:o},350:function(t,e,n){var i=n(1),r=n(318);t.exports=function(t){return i((function(){return!!r[t]()||"​…᠎"!="​…᠎"[t]()||r[t].name!==t}))}},351:function(t,e,n){var i=n(4),r=n(73);t.exports=function(t,e,n){var a,s;return r&&"function"==typeof(a=e.constructor)&&a!==n&&i(s=a.prototype)&&s!==n.prototype&&r(t,s),t}},352:function(t,e,n){"use strict";var i,r=n(0),a=n(24).f,s=n(12),o=n(18),u=n(107),l=n(22),c=n(108),h=n(19),f="".endsWith,p=Math.min,d=c("endsWith");r({target:"String",proto:!0,forced:!!(h||d||(i=a(String.prototype,"endsWith"),!i||i.writable))&&!d},{endsWith:function(t){var e=o(l(this));u(t);var n=arguments.length>1?arguments[1]:void 0,i=s(e.length),r=void 0===n?i:p(s(n),i),a=o(t);return f?f.call(e,a,r):e.slice(r-a.length,r)===a}})},353:function(t,e,n){"use strict";var i=n(319);n.n(i).a},354:function(t,e,n){"use strict";var i=n(320);n.n(i).a},355:function(t,e,n){"use strict";var i=n(321);n.n(i).a},356:function(t,e,n){"use strict";var i=n(322);n.n(i).a},357:function(t,e,n){"use strict";var i=n(323);n.n(i).a},358:function(t,e,n){"use strict";var i=n(324);n.n(i).a},359:function(t,e,n){"use strict";var i=n(325);n.n(i).a},360:function(t,e,n){var i=n(31),r=n(14),a=n(25);t.exports=function(t){return"string"==typeof t||!r(t)&&a(t)&&"[object String]"==i(t)}},361:function(t,e,n){"use strict";var i=n(326);n.n(i).a},362:function(t,e,n){"use strict";var i=n(327);n.n(i).a},363:function(t,e,n){"use strict";var i=n(328);n.n(i).a},364:function(t,e,n){"use strict";var i=n(0),r=n(30).find,a=n(104),s=!0;"find"in[]&&Array(1).find((function(){s=!1})),i({target:"Array",proto:!0,forced:s},{find:function(t){return r(this,t,arguments.length>1?arguments[1]:void 0)}}),a("find")},365:function(t,e,n){"use strict";var i=n(329);n.n(i).a},366:function(t,e,n){"use strict";var i=n(330);n.n(i).a},373:function(t,e,n){"use strict";n(98),n(100),n(344);var i=n(314),r={name:"NavLink",props:{item:{required:!0}},computed:{link:function(){return Object(i.b)(this.item.link)},exact:function(){var t=this;return this.$site.locales?Object.keys(this.$site.locales).some((function(e){return e===t.link})):"/"===this.link},isNonHttpURI:function(){return Object(i.g)(this.link)||Object(i.h)(this.link)},isBlankTarget:function(){return"_blank"===this.target},isInternal:function(){return!Object(i.f)(this.link)&&!this.isBlankTarget},target:function(){return this.isNonHttpURI?null:this.item.target?this.item.target:Object(i.f)(this.link)?"_blank":""},rel:function(){return this.isNonHttpURI||!1===this.item.rel?null:this.item.rel?this.item.rel:this.isBlankTarget?"noopener noreferrer":null}},methods:{focusoutAction:function(){this.$emit("focusout")}}},a=n(44),s=Object(a.a)(r,(function(){var t=this,e=t.$createElement,n=t._self._c||e;return t.isInternal?n("RouterLink",{staticClass:"nav-link",attrs:{to:t.link,exact:t.exact},nativeOn:{focusout:function(e){return t.focusoutAction(e)}}},[t._v("\n "+t._s(t.item.text)+"\n")]):n("a",{staticClass:"nav-link external",attrs:{href:t.link,target:t.target,rel:t.rel},on:{focusout:t.focusoutAction}},[t._v("\n "+t._s(t.item.text)+"\n "),t.isBlankTarget?n("OutboundLink"):t._e()],1)}),[],!1,null,null,null).exports,o={name:"Home",components:{NavLink:s},computed:{data:function(){return this.$page.frontmatter},actionLink:function(){return{link:this.data.actionLink,text:this.data.actionText}}}},u=(n(347),Object(a.a)(o,(function(){var t=this,e=t.$createElement,n=t._self._c||e;return n("main",{staticClass:"home",attrs:{"aria-labelledby":null!==t.data.heroText?"main-title":null}},[n("header",{staticClass:"hero"},[t.data.heroImage?n("img",{attrs:{src:t.$withBase(t.data.heroImage),alt:t.data.heroAlt||"hero"}}):t._e(),t._v(" "),null!==t.data.heroText?n("h1",{attrs:{id:"main-title"}},[t._v("\n "+t._s(t.data.heroText||t.$title||"Hello")+"\n ")]):t._e(),t._v(" "),null!==t.data.tagline?n("p",{staticClass:"description"},[t._v("\n "+t._s(t.data.tagline||t.$description||"Welcome to your VuePress site")+"\n ")]):t._e(),t._v(" "),t.data.actionText&&t.data.actionLink?n("p",{staticClass:"action"},[n("NavLink",{staticClass:"action-button",attrs:{item:t.actionLink}})],1):t._e()]),t._v(" "),t.data.features&&t.data.features.length?n("div",{staticClass:"features"},t._l(t.data.features,(function(e,i){return n("div",{key:i,staticClass:"feature"},[n("h2",[t._v(t._s(e.title))]),t._v(" "),n("p",[t._v(t._s(e.details))])])})),0):t._e(),t._v(" "),n("Content",{staticClass:"theme-default-content custom"}),t._v(" "),t.data.footer?n("div",{staticClass:"footer"},[t._v("\n "+t._s(t.data.footer)+"\n ")]):t._e()],1)}),[],!1,null,null,null).exports),l=(n(348),n(29),n(178),n(169),n(102),n(45),n(181),n(316),n(338),n(176),n(71),n(339),n(103),n(352),n(72),n(336),n(182)),c=n.n(l),h=function(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null,i=c()(e,"title","");return c()(e,"frontmatter.tags")&&(i+=" ".concat(e.frontmatter.tags.join(" "))),n&&(i+=" ".concat(n)),f(t,i)},f=function(t,e){var n=function(t){return t.replace(/[-/\\^$*+?.()|[\]{}]/g,"\\$&")},i=new RegExp("[^\0-]"),r=t.split(/\s+/g).map((function(t){return t.trim()})).filter((function(t){return!!t}));if(i.test(t))return r.some((function(t){return e.toLowerCase().indexOf(t)>-1}));var a=t.endsWith(" ");return new RegExp(r.map((function(t,e){return r.length!==e+1||a?"(?=.*\\b".concat(n(t),"\\b)"):"(?=.*\\b".concat(n(t),")")})).join("")+".+","gi").test(e)},p={name:"SearchBox",data:function(){return{query:"",focused:!1,focusIndex:0,placeholder:void 0}},computed:{showSuggestions:function(){return this.focused&&this.suggestions&&this.suggestions.length},suggestions:function(){var t=this.query.trim().toLowerCase();if(t){for(var e=this.$site.pages,n=this.$site.themeConfig.searchMaxSuggestions||5,i=this.$localePath,r=[],a=0;a=n);a++){var s=e[a];if(this.getPageLocalePath(s)===i&&this.isSearchable(s))if(h(t,s))r.push(s);else if(s.headers)for(var o=0;o=n);o++){var u=s.headers[o];u.title&&h(t,s,u.title)&&r.push(Object.assign({},s,{path:s.path+"#"+u.slug,header:u}))}}return r}},alignRight:function(){return(this.$site.themeConfig.nav||[]).length+(this.$site.repo?1:0)<=2}},mounted:function(){this.placeholder=this.$site.themeConfig.searchPlaceholder||"",document.addEventListener("keydown",this.onHotkey)},beforeDestroy:function(){document.removeEventListener("keydown",this.onHotkey)},methods:{getPageLocalePath:function(t){for(var e in this.$site.locales||{})if("/"!==e&&0===t.path.indexOf(e))return e;return"/"},isSearchable:function(t){var e=null;return null===e||(e=Array.isArray(e)?e:new Array(e)).filter((function(e){return t.path.match(e)})).length>0},onHotkey:function(t){t.srcElement===document.body&&["s","/"].includes(t.key)&&(this.$refs.input.focus(),t.preventDefault())},onUp:function(){this.showSuggestions&&(this.focusIndex>0?this.focusIndex--:this.focusIndex=this.suggestions.length-1)},onDown:function(){this.showSuggestions&&(this.focusIndex "+t._s(e.header.title))]):t._e()])])})),0):t._e()])}),[],!1,null,null,null).exports),g=(n(354),Object(a.a)({},(function(){var t=this,e=t.$createElement,n=t._self._c||e;return n("div",{staticClass:"sidebar-button",on:{click:function(e){return t.$emit("toggle-sidebar")}}},[n("svg",{staticClass:"icon",attrs:{xmlns:"http://www.w3.org/2000/svg","aria-hidden":"true",role:"img",viewBox:"0 0 448 512"}},[n("path",{attrs:{fill:"currentColor",d:"M436 124H12c-6.627 0-12-5.373-12-12V80c0-6.627 5.373-12 12-12h424c6.627 0 12 5.373 12 12v32c0 6.627-5.373 12-12 12zm0 160H12c-6.627 0-12-5.373-12-12v-32c0-6.627 5.373-12 12-12h424c6.627 0 12 5.373 12 12v32c0 6.627-5.373 12-12 12zm0 160H12c-6.627 0-12-5.373-12-12v-32c0-6.627 5.373-12 12-12h424c6.627 0 12 5.373 12 12v32c0 6.627-5.373 12-12 12z"}})])])}),[],!1,null,null,null).exports),v=(n(175),n(42)),m=n(342),b=n(183),k=n.n(b),_={name:"DropdownLink",components:{NavLink:s,DropdownTransition:m.a},props:{item:{required:!0}},data:function(){return{open:!1}},computed:{dropdownAriaLabel:function(){return this.item.ariaLabel||this.item.text}},watch:{$route:function(){this.open=!1}},methods:{setOpen:function(t){this.open=t},isLastItemOfArray:function(t,e){return k()(e)===t},handleDropdown:function(){0===event.detail&&this.setOpen(!this.open)}}},x=(n(356),{name:"NavLinks",components:{NavLink:s,DropdownLink:Object(a.a)(_,(function(){var t=this,e=t.$createElement,n=t._self._c||e;return n("div",{staticClass:"dropdown-wrapper",class:{open:t.open}},[n("button",{staticClass:"dropdown-title",attrs:{type:"button","aria-label":t.dropdownAriaLabel},on:{click:t.handleDropdown}},[n("span",{staticClass:"title"},[t._v(t._s(t.item.text))]),t._v(" "),n("span",{staticClass:"arrow down"})]),t._v(" "),n("button",{staticClass:"mobile-dropdown-title",attrs:{type:"button","aria-label":t.dropdownAriaLabel},on:{click:function(e){return t.setOpen(!t.open)}}},[n("span",{staticClass:"title"},[t._v(t._s(t.item.text))]),t._v(" "),n("span",{staticClass:"arrow",class:t.open?"down":"right"})]),t._v(" "),n("DropdownTransition",[n("ul",{directives:[{name:"show",rawName:"v-show",value:t.open,expression:"open"}],staticClass:"nav-dropdown"},t._l(t.item.items,(function(e,i){return n("li",{key:e.link||i,staticClass:"dropdown-item"},["links"===e.type?n("h4",[t._v("\n "+t._s(e.text)+"\n ")]):t._e(),t._v(" "),"links"===e.type?n("ul",{staticClass:"dropdown-subitem-wrapper"},t._l(e.items,(function(i){return n("li",{key:i.link,staticClass:"dropdown-subitem"},[n("NavLink",{attrs:{item:i},on:{focusout:function(n){t.isLastItemOfArray(i,e.items)&&t.isLastItemOfArray(e,t.item.items)&&t.setOpen(!1)}}})],1)})),0):n("NavLink",{attrs:{item:e},on:{focusout:function(n){t.isLastItemOfArray(e,t.item.items)&&t.setOpen(!1)}}})],1)})),0)])],1)}),[],!1,null,null,null).exports},computed:{userNav:function(){return this.$themeLocaleConfig.nav||this.$site.themeConfig.nav||[]},nav:function(){var t=this,e=this.$site.locales;if(e&&Object.keys(e).length>1){var n=this.$page.path,i=this.$router.options.routes,r=this.$site.themeConfig.locales||{},a={text:this.$themeLocaleConfig.selectText||"Languages",ariaLabel:this.$themeLocaleConfig.ariaLabel||"Select language",items:Object.keys(e).map((function(a){var s,o=e[a],u=r[a]&&r[a].label||o.lang;return o.lang===t.$lang?s=n:(s=n.replace(t.$localeConfig.path,a),i.some((function(t){return t.path===s}))||(s=a)),{text:u,link:s}}))};return[].concat(Object(v.a)(this.userNav),[a])}return this.userNav},userLinks:function(){return(this.nav||[]).map((function(t){return Object.assign(Object(i.j)(t),{items:(t.items||[]).map(i.j)})}))},repoLink:function(){var t=this.$site.themeConfig.repo;return t?/^https?:/.test(t)?t:"https://github.com/".concat(t):null},repoLabel:function(){if(this.repoLink){if(this.$site.themeConfig.repoLabel)return this.$site.themeConfig.repoLabel;for(var t=this.repoLink.match(/^https?:\/\/[^/]+/)[0],e=["GitHub","GitLab","Bitbucket"],n=0;nMath.abs(n)&&Math.abs(e)>40&&(e>0&&this.touchStart.x<=80?this.toggleSidebar(!0):this.toggleSidebar(!1))}}}),G=Object(a.a)(W,(function(){var t=this,e=t.$createElement,n=t._self._c||e;return n("div",{staticClass:"theme-container",class:t.pageClasses,on:{touchstart:t.onTouchStart,touchend:t.onTouchEnd}},[t.shouldShowNavbar?n("Navbar",{on:{"toggle-sidebar":t.toggleSidebar}}):t._e(),t._v(" "),n("div",{staticClass:"sidebar-mask",on:{click:function(e){return t.toggleSidebar(!1)}}}),t._v(" "),n("Sidebar",{attrs:{items:t.sidebarItems},on:{"toggle-sidebar":t.toggleSidebar},scopedSlots:t._u([{key:"top",fn:function(){return[t._t("sidebar-top")]},proxy:!0},{key:"bottom",fn:function(){return[t._t("sidebar-bottom")]},proxy:!0}],null,!0)}),t._v(" "),t.$page.frontmatter.home?n("Home"):n("Page",{attrs:{"sidebar-items":t.sidebarItems},scopedSlots:t._u([{key:"top",fn:function(){return[t._t("page-top")]},proxy:!0},{key:"bottom",fn:function(){return[t._t("page-bottom")]},proxy:!0}],null,!0)})],1)}),[],!1,null,null,null);e.a=G.exports}}]); \ No newline at end of file diff --git a/assets/js/20.7d9d9bba.js b/assets/js/20.7d9d9bba.js new file mode 100644 index 000000000..a08e1b902 --- /dev/null +++ b/assets/js/20.7d9d9bba.js @@ -0,0 +1 @@ +(window.webpackJsonp=window.webpackJsonp||[]).push([[20],{470:function(t,s,a){"use strict";a.r(s);var e=a(44),n=Object(e.a)({},(function(){var t=this,s=t.$createElement,a=t._self._c||s;return a("ContentSlotsDistributor",{attrs:{"slot-key":t.$parent.slotKey}},[a("h1",{attrs:{id:"locale-messages-syntax"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#locale-messages-syntax"}},[t._v("#")]),t._v(" Locale messages syntax")]),t._v(" "),a("h2",{attrs:{id:"structure"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#structure"}},[t._v("#")]),t._v(" Structure")]),t._v(" "),a("p",[t._v("Locale Messages syntax below:")]),t._v(" "),a("div",{staticClass:"language-typescript extra-class"},[a("pre",{pre:!0,attrs:{class:"language-typescript"}},[a("code",[a("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// As Flowtype definition, Locale Messages syntax like BNF annotation")]),t._v("\n"),a("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("type")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token class-name"}},[t._v("LocaleMessages")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("[")]),t._v("key"),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" Locale"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("]")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" LocaleMessageObject "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n"),a("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("type")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token class-name"}},[t._v("LocaleMessageObject")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("[")]),t._v("key"),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" Path"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("]")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" LocaleMessage "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n"),a("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("type")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token class-name"}},[t._v("LocaleMessageArray")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" LocaleMessage"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("[")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("]")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n"),a("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("type")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token class-name"}},[t._v("MessageContext")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token function-variable function"}},[t._v("list")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v("index"),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token builtin"}},[t._v("number")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=>")]),t._v(" mixed"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token function-variable function"}},[t._v("named")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v("key"),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token builtin"}},[t._v("string")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=>")]),t._v(" mixed"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token function-variable function"}},[t._v("linked")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v("key"),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token builtin"}},[t._v("string")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=>")]),t._v(" TranslateResult"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n values"),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token builtin"}},[t._v("any")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// NOTE: not compatible for vue-i18n@v9.x")]),t._v("\n path"),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token builtin"}},[t._v("string")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// NOTE: not compatible for vue-i18n@v9.x")]),t._v("\n formatter"),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" Formatter"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// NOTE: not compatible for vue-i18n@v9.x")]),t._v("\n messages"),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" LocaleMessages"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// NOTE: not compatible for vue-i18n@v9.x")]),t._v("\n locale"),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" Locale "),a("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// NOTE: not compatible for vue-i18n@v9.x")]),t._v("\n"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n"),a("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("type")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token class-name"}},[t._v("MessageFunction")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v("ctx"),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" MessageContext"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=>")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token builtin"}},[t._v("string")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n"),a("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("type")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token class-name"}},[t._v("LocaleMessage")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token builtin"}},[t._v("string")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v("|")]),t._v(" MessageFunction "),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v("|")]),t._v(" LocaleMessageObject "),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v("|")]),t._v(" LocaleMessageArray"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n"),a("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("type")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token class-name"}},[t._v("Locale")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token builtin"}},[t._v("string")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n"),a("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("type")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token class-name"}},[t._v("Path")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token builtin"}},[t._v("string")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n")])])]),a("p",[t._v("Based on the above syntax, You can configure the following Locale Messages structure:")]),t._v(" "),a("div",{staticClass:"language-json extra-class"},[a("pre",{pre:!0,attrs:{class:"language-json"}},[a("code",[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token property"}},[t._v('"en"')]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// 'en' Locale")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token property"}},[t._v('"key1"')]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v('"this is message1"')]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// basic")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token property"}},[t._v('"nested"')]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// nested")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token property"}},[t._v('"message1"')]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v('"this is nested message1"')]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token property"}},[t._v('"errors"')]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("[")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// array")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v('"this is 0 error code message"')]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// object in array")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token property"}},[t._v('"internal1"')]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v('"this is internal 1 error message"')]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("[")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// array in array")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v('"this is nested array error 1"')]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("]")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("]")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token property"}},[t._v('"ja"')]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// 'ja' Locale")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// ...")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n")])])]),a("p",[t._v("In the above Locale Messages structure, You can translate using below key paths.")]),t._v(" "),a("div",{staticClass:"language-html extra-class"},[a("pre",{pre:!0,attrs:{class:"language-html"}},[a("code",[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("div")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v("id")]),a("span",{pre:!0,attrs:{class:"token attr-value"}},[a("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),t._v("app"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token comment"}},[t._v("\x3c!-- basic --\x3e")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("p")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("{{ $t('key1') }}"),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token comment"}},[t._v("\x3c!-- nested --\x3e")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("p")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("{{ $t('nested.message1') }}"),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token comment"}},[t._v("\x3c!-- array --\x3e")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("p")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("{{ $t('errors[0]') }}"),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token comment"}},[t._v("\x3c!-- object in array --\x3e")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("p")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("{{ $t('errors[1].internal1') }}"),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token comment"}},[t._v("\x3c!-- array in array --\x3e")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("p")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("{{ $t('errors[2][0]') }}"),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n"),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n")])])]),a("p",[t._v("Output the following:")]),t._v(" "),a("div",{staticClass:"language-html extra-class"},[a("pre",{pre:!0,attrs:{class:"language-html"}},[a("code",[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("div")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v("id")]),a("span",{pre:!0,attrs:{class:"token attr-value"}},[a("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),t._v("app"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token comment"}},[t._v("\x3c!-- basic --\x3e")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("p")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("this is message1"),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token comment"}},[t._v("\x3c!-- nested --\x3e")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("p")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("this is nested message1"),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token comment"}},[t._v("\x3c!-- array --\x3e")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("p")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("this is 0 error code message"),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token comment"}},[t._v("\x3c!-- object in array --\x3e")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("p")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("this is internal 1 error message"),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token comment"}},[t._v("\x3c!-- array in array --\x3e")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("p")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("this is nested array error 1"),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n"),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n")])])]),a("h2",{attrs:{id:"linked-locale-messages"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#linked-locale-messages"}},[t._v("#")]),t._v(" Linked locale messages")]),t._v(" "),a("p",[t._v("If there's a translation key that will always have the same concrete text as another one you can just link to it. To link to another translation key, all you have to do is to prefix its contents with an "),a("code",[t._v("@:")]),t._v(" sign followed by the full name of the translation key including the namespace you want to link to.")]),t._v(" "),a("p",[t._v("Locale messages the below:")]),t._v(" "),a("div",{staticClass:"language-js extra-class"},[a("pre",{pre:!0,attrs:{class:"language-js"}},[a("code",[a("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("const")]),t._v(" messages "),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("en")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("message")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("the_world")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v("'the world'")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("dio")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v("'DIO:'")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("linked")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v("'@:message.dio @:message.the_world !!!!'")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n")])])]),a("p",[t._v("Template:")]),t._v(" "),a("div",{staticClass:"language-html extra-class"},[a("pre",{pre:!0,attrs:{class:"language-html"}},[a("code",[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("p")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("{{ $t('message.linked') }}"),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n")])])]),a("p",[t._v("Output:")]),t._v(" "),a("div",{staticClass:"language-html extra-class"},[a("pre",{pre:!0,attrs:{class:"language-html"}},[a("code",[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("p")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("DIO: the world !!!!"),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n")])])]),a("h3",{attrs:{id:"formatting-linked-locale-messages"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#formatting-linked-locale-messages"}},[t._v("#")]),t._v(" Formatting linked locale messages")]),t._v(" "),a("p",[t._v("If the language distinguish cases of character, you may need control the case of the linked locale messages.\nLinked messages can be formatted with modifier "),a("code",[t._v("@.modifier:key")])]),t._v(" "),a("p",[t._v("The below modifiers are available currently.")]),t._v(" "),a("ul",[a("li",[a("code",[t._v("upper")]),t._v(": Uppercase all characters in the linked message.")]),t._v(" "),a("li",[a("code",[t._v("lower")]),t._v(": Lowercase all characters in the linked message.")]),t._v(" "),a("li",[a("code",[t._v("capitalize")]),t._v(": Capitalize the first character in the linked message.")])]),t._v(" "),a("p",[t._v("Locale messages the below:")]),t._v(" "),a("div",{staticClass:"language-javascript extra-class"},[a("pre",{pre:!0,attrs:{class:"language-javascript"}},[a("code",[a("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("const")]),t._v(" messages "),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("en")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("message")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("homeAddress")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v("'Home address'")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("missingHomeAddress")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v("'Please provide @.lower:message.homeAddress'")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n")])])]),a("div",{staticClass:"language-html extra-class"},[a("pre",{pre:!0,attrs:{class:"language-html"}},[a("code",[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("label")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("{{ $t('message.homeAddress') }}"),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n\n"),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("p")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v("class")]),a("span",{pre:!0,attrs:{class:"token attr-value"}},[a("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),t._v("error"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("{{ $t('message.missingHomeAddress') }}"),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n")])])]),a("p",[t._v("Output the below:")]),t._v(" "),a("div",{staticClass:"language-html extra-class"},[a("pre",{pre:!0,attrs:{class:"language-html"}},[a("code",[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("label")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("Home address"),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n\n"),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("p")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v("class")]),a("span",{pre:!0,attrs:{class:"token attr-value"}},[a("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),t._v("error"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("Please provide home address"),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n")])])]),a("p",[t._v("You can add modifiers or overwrite the existing ones passing the "),a("code",[t._v("modifiers")]),t._v(" options to the "),a("code",[t._v("VueI18n")]),t._v(" constructor.")]),t._v(" "),a("div",{staticClass:"language-javascript extra-class"},[a("pre",{pre:!0,attrs:{class:"language-javascript"}},[a("code",[a("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("const")]),t._v(" i18n "),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("new")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token class-name"}},[t._v("VueI18n")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("locale")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v("'en'")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("modifiers")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// Adding a new modifier")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token function-variable function"}},[t._v("snakeCase")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),a("span",{pre:!0,attrs:{class:"token parameter"}},[t._v("str")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=>")]),t._v(" str"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),a("span",{pre:!0,attrs:{class:"token function"}},[t._v("split")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),a("span",{pre:!0,attrs:{class:"token string"}},[t._v("' '")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),a("span",{pre:!0,attrs:{class:"token function"}},[t._v("join")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),a("span",{pre:!0,attrs:{class:"token string"}},[t._v("'-'")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("messages")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// ...")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v("\n")])])]),a("h3",{attrs:{id:"grouping-by-brackets"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#grouping-by-brackets"}},[t._v("#")]),t._v(" Grouping by brackets")]),t._v(" "),a("p",[t._v("A translation key of linked locale message can also have the form of "),a("code",[t._v("@:(message.foo.bar.baz)")]),t._v(" in which the link to another translation key is within brackets "),a("code",[t._v("()")]),t._v(".")]),t._v(" "),a("p",[t._v("This can be useful if the link "),a("code",[t._v("@:message.something")]),t._v(" is followed by period "),a("code",[t._v(".")]),t._v(", which otherwise would be part of the link and may not need to be.")]),t._v(" "),a("p",[t._v("Locale messages:")]),t._v(" "),a("div",{staticClass:"language-js extra-class"},[a("pre",{pre:!0,attrs:{class:"language-js"}},[a("code",[a("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("const")]),t._v(" messages "),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("en")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("message")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("dio")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v("'DIO'")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("linked")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v("'There\\'s a reason, you lost, @:(message.dio).'")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n")])])]),a("p",[t._v("Template:")]),t._v(" "),a("div",{staticClass:"language-html extra-class"},[a("pre",{pre:!0,attrs:{class:"language-html"}},[a("code",[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("p")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("{{ $t('message.linked') }}"),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n")])])]),a("p",[t._v("Output:")]),t._v(" "),a("div",{staticClass:"language-html extra-class"},[a("pre",{pre:!0,attrs:{class:"language-html"}},[a("code",[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("p")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("There's a reason, you lost, DIO."),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n")])])]),a("h2",{attrs:{id:"message-function"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#message-function"}},[t._v("#")]),t._v(" Message Function")]),t._v(" "),a("p",[t._v("vue-i18n recommends using the string base on list or named format as locale messages when translating messages.")]),t._v(" "),a("p",[t._v("There are situations however, where you really need the full programmatic power of JavaScript, due to the complex language syntax. So instead of string-based messages, you can use the "),a("strong",[t._v("message function")]),t._v(".")]),t._v(" "),a("p",[t._v("The following is a message function that returns a simple greeting:")]),t._v(" "),a("div",{staticClass:"language-js extra-class"},[a("pre",{pre:!0,attrs:{class:"language-js"}},[a("code",[a("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("const")]),t._v(" messages "),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("en")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token function-variable function"}},[t._v("greeting")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),a("span",{pre:!0,attrs:{class:"token parameter"}},[t._v("ctx")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=>")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v("'hello!'")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n")])])]),a("p",[t._v("The use of the message function is very easy! You just specify the key of the message function with "),a("code",[t._v("$t")]),t._v(" or "),a("code",[t._v("t")]),t._v(":")]),t._v(" "),a("div",{staticClass:"language-html extra-class"},[a("pre",{pre:!0,attrs:{class:"language-html"}},[a("code",[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("p")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("{{ $t('greeting') }}"),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n")])])]),a("p",[t._v("Output is the below:")]),t._v(" "),a("div",{staticClass:"language-html extra-class"},[a("pre",{pre:!0,attrs:{class:"language-html"}},[a("code",[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("p")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("hello!"),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n")])])]),a("p",[t._v("The message function outputs the message of the return value of the message function.")]),t._v(" "),a("h3",{attrs:{id:"named-formatting"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#named-formatting"}},[t._v("#")]),t._v(" Named formatting")]),t._v(" "),a("p",[t._v("vue-i18n supports "),a("RouterLink",{attrs:{to:"/guide/formatting.html#named-formatting"}},[t._v("named formatting")]),t._v(" as a string-based message format. vue-i18n interpolate the parameter values with "),a("code",[t._v("$t")]),t._v(" or "),a("code",[t._v("t")]),t._v(", and it can be output it.")],1),t._v(" "),a("p",[t._v("You can do the same thing with the message function by using "),a("strong",[t._v("message context")]),t._v(":")]),t._v(" "),a("p",[t._v("here is the example of greeting:")]),t._v(" "),a("div",{staticClass:"language-js extra-class"},[a("pre",{pre:!0,attrs:{class:"language-js"}},[a("code",[a("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("const")]),t._v(" messages "),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("en")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token function-variable function"}},[t._v("greeting")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),a("span",{pre:!0,attrs:{class:"token parameter"}},[t._v("ctx")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=>")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token template-string"}},[a("span",{pre:!0,attrs:{class:"token template-punctuation string"}},[t._v("`")]),a("span",{pre:!0,attrs:{class:"token string"}},[t._v("hello, ")]),a("span",{pre:!0,attrs:{class:"token interpolation"}},[a("span",{pre:!0,attrs:{class:"token interpolation-punctuation punctuation"}},[t._v("${")]),t._v("ctx"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),a("span",{pre:!0,attrs:{class:"token function"}},[t._v("named")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),a("span",{pre:!0,attrs:{class:"token string"}},[t._v("'name'")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),a("span",{pre:!0,attrs:{class:"token interpolation-punctuation punctuation"}},[t._v("}")])]),a("span",{pre:!0,attrs:{class:"token string"}},[t._v("!")]),a("span",{pre:!0,attrs:{class:"token template-punctuation string"}},[t._v("`")])]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n")])])]),a("p",[t._v("Template:")]),t._v(" "),a("div",{staticClass:"language-html extra-class"},[a("pre",{pre:!0,attrs:{class:"language-html"}},[a("code",[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("p")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("{{ $t('greeting', { name: 'DIO' }) }}"),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n")])])]),a("p",[t._v("Output is the below:")]),t._v(" "),a("div",{staticClass:"language-html extra-class"},[a("pre",{pre:!0,attrs:{class:"language-html"}},[a("code",[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("p")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("hello, DIO!"),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n")])])]),a("p",[t._v("The message context has a named function. You need to specify the key that resolves the value specified with the named of "),a("code",[t._v("$t")]),t._v(" or "),a("code",[t._v("t")]),t._v(".")]),t._v(" "),a("h3",{attrs:{id:"list-formatting"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#list-formatting"}},[t._v("#")]),t._v(" List formatting")]),t._v(" "),a("p",[t._v("The use of the list format is similar to the named format described above.")]),t._v(" "),a("p",[t._v("vue-i18n supports "),a("RouterLink",{attrs:{to:"/guide/formatting.html#list-formatting"}},[t._v("list formatting")]),t._v(" as a string-based message format. vue-i18n interpolate the parameter values with "),a("code",[t._v("$t")]),t._v(" or "),a("code",[t._v("t")]),t._v(", and it can be output it.")],1),t._v(" "),a("p",[t._v("You can do the same thing with the message function by using message context:")]),t._v(" "),a("p",[t._v("here is the example of greeting:")]),t._v(" "),a("div",{staticClass:"language-js extra-class"},[a("pre",{pre:!0,attrs:{class:"language-js"}},[a("code",[a("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("const")]),t._v(" messages "),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("en")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token function-variable function"}},[t._v("greeting")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),a("span",{pre:!0,attrs:{class:"token parameter"}},[t._v("ctx")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=>")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token template-string"}},[a("span",{pre:!0,attrs:{class:"token template-punctuation string"}},[t._v("`")]),a("span",{pre:!0,attrs:{class:"token string"}},[t._v("hello, ")]),a("span",{pre:!0,attrs:{class:"token interpolation"}},[a("span",{pre:!0,attrs:{class:"token interpolation-punctuation punctuation"}},[t._v("${")]),t._v("ctx"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),a("span",{pre:!0,attrs:{class:"token function"}},[t._v("list")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),a("span",{pre:!0,attrs:{class:"token number"}},[t._v("0")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),a("span",{pre:!0,attrs:{class:"token interpolation-punctuation punctuation"}},[t._v("}")])]),a("span",{pre:!0,attrs:{class:"token string"}},[t._v("!")]),a("span",{pre:!0,attrs:{class:"token template-punctuation string"}},[t._v("`")])]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n")])])]),a("p",[t._v("Template:")]),t._v(" "),a("div",{staticClass:"language-html extra-class"},[a("pre",{pre:!0,attrs:{class:"language-html"}},[a("code",[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("p")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("{{ $t('greeting', ['DIO']) }}"),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n")])])]),a("p",[t._v("Output is the below:")]),t._v(" "),a("div",{staticClass:"language-html extra-class"},[a("pre",{pre:!0,attrs:{class:"language-html"}},[a("code",[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("p")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("hello, DIO!"),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n")])])]),a("p",[t._v("The message context has a list function. You need to specify the index that resolves the value specified with the list of "),a("code",[t._v("$t")]),t._v(" or "),a("code",[t._v("t")]),t._v(".")]),t._v(" "),a("h3",{attrs:{id:"limitation"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#limitation"}},[t._v("#")]),t._v(" Limitation")]),t._v(" "),a("p",[t._v("In the message function, the following functions, which are provided on a string basis, are not available via a message context:")]),t._v(" "),a("ul",[a("li",[t._v("Pluralization")])]),t._v(" "),a("p",[t._v("And also, the following props of message context is not compatible for vue-i18 v9.x or later:")]),t._v(" "),a("ul",[a("li",[a("code",[t._v("path")])]),t._v(" "),a("li",[a("code",[t._v("locale")])]),t._v(" "),a("li",[a("code",[t._v("messages")])]),t._v(" "),a("li",[a("code",[t._v("formatter")])])]),t._v(" "),a("p",[t._v("If you are using these message context props means that it will be difficult to migrate to vue-i18n v9.x or later.")])])}),[],!1,null,null,null);s.default=n.exports}}]); \ No newline at end of file diff --git a/assets/js/21.bd95e2eb.js b/assets/js/21.bd95e2eb.js new file mode 100644 index 000000000..46666c952 --- /dev/null +++ b/assets/js/21.bd95e2eb.js @@ -0,0 +1 @@ +(window.webpackJsonp=window.webpackJsonp||[]).push([[21],{471:function(t,a,s){"use strict";s.r(a);var n=s(44),e=Object(n.a)({},(function(){var t=this,a=t.$createElement,s=t._self._c||a;return s("ContentSlotsDistributor",{attrs:{"slot-key":t.$parent.slotKey}},[s("h1",{attrs:{id:"number-localization"}},[s("a",{staticClass:"header-anchor",attrs:{href:"#number-localization"}},[t._v("#")]),t._v(" Number localization")]),t._v(" "),s("div",{staticClass:"custom-block tip"},[s("p",{staticClass:"custom-block-title"},[t._v("Support Version")]),t._v(" "),s("p",[t._v("🆕 7.0+")])]),t._v(" "),s("p",[t._v("You can localize the number with your definition formats.")]),t._v(" "),s("p",[t._v("Number formats the below:")]),t._v(" "),s("div",{staticClass:"language-js extra-class"},[s("pre",{pre:!0,attrs:{class:"language-js"}},[s("code",[s("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("const")]),t._v(" numberFormats "),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token string-property property"}},[t._v("'en-US'")]),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("currency")]),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("style")]),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token string"}},[t._v("'currency'")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("currency")]),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token string"}},[t._v("'USD'")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token string-property property"}},[t._v("'ja-JP'")]),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("currency")]),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("style")]),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token string"}},[t._v("'currency'")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("currency")]),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token string"}},[t._v("'JPY'")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("currencyDisplay")]),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token string"}},[t._v("'symbol'")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n")])])]),s("p",[t._v("As the above, you can define named number formats (e.g. "),s("code",[t._v("currency")]),t._v(", etc), and you need to use "),s("a",{attrs:{href:"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NumberFormat",target:"_blank",rel:"noopener noreferrer"}},[t._v("the options with ECMA-402 Intl.NumberFormat"),s("OutboundLink")],1)]),t._v(" "),s("p",[t._v("After that, when using the locale messages, you need to specify the "),s("code",[t._v("numberFormats")]),t._v(" option of the "),s("code",[t._v("VueI18n")]),t._v(" constructor:")]),t._v(" "),s("div",{staticClass:"language-js extra-class"},[s("pre",{pre:!0,attrs:{class:"language-js"}},[s("code",[s("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("const")]),t._v(" i18n "),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("new")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token class-name"}},[t._v("VueI18n")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n numberFormats\n"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v("\n\n"),s("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("new")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token class-name"}},[t._v("Vue")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n i18n\n"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),s("span",{pre:!0,attrs:{class:"token function"}},[t._v("$mount")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),s("span",{pre:!0,attrs:{class:"token string"}},[t._v("'#app'")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v("\n")])])]),s("p",[t._v("Template the below:")]),t._v(" "),s("div",{staticClass:"language-html extra-class"},[s("pre",{pre:!0,attrs:{class:"language-html"}},[s("code",[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("div")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v("id")]),s("span",{pre:!0,attrs:{class:"token attr-value"}},[s("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),t._v("app"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("p")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("{{ $n(100, 'currency') }}"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("p")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("{{ $n(100, 'currency', 'ja-JP') }}"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n")])])]),s("p",[t._v("Output the below:")]),t._v(" "),s("div",{staticClass:"language-html extra-class"},[s("pre",{pre:!0,attrs:{class:"language-html"}},[s("code",[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("div")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v("id")]),s("span",{pre:!0,attrs:{class:"token attr-value"}},[s("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),t._v("app"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("p")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("$100.00"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("p")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("¥100"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n")])])]),s("h2",{attrs:{id:"custom-formatting"}},[s("a",{staticClass:"header-anchor",attrs:{href:"#custom-formatting"}},[t._v("#")]),t._v(" Custom formatting")]),t._v(" "),s("div",{staticClass:"custom-block tip"},[s("p",{staticClass:"custom-block-title"},[t._v("Support Version")]),t._v(" "),s("p",[t._v("🆕 8.10+")])]),t._v(" "),s("p",[s("code",[t._v("$n")]),t._v(" method returns resulting string with fully formatted number, which can only be used as a whole. In situations when you need to style some part of the formatted number (like fraction digits), "),s("code",[t._v("$n")]),t._v(" is not enough. In such cases "),s("code",[t._v("")]),t._v(" functional component will be of help.")]),t._v(" "),s("p",[t._v("With a minimum set of properties, "),s("code",[t._v("")]),t._v(" generates the same output as "),s("code",[t._v("$n")]),t._v(", wrapped into configured DOM element.")]),t._v(" "),s("p",[t._v("The following template:")]),t._v(" "),s("div",{staticClass:"language-html extra-class"},[s("pre",{pre:!0,attrs:{class:"language-html"}},[s("code",[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("div")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v("id")]),s("span",{pre:!0,attrs:{class:"token attr-value"}},[s("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),t._v("app"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("i18n-n")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v(":value")]),s("span",{pre:!0,attrs:{class:"token attr-value"}},[s("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),t._v("100"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("i18n-n")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v(":value")]),s("span",{pre:!0,attrs:{class:"token attr-value"}},[s("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),t._v("100"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])]),t._v(" "),s("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v("format")]),s("span",{pre:!0,attrs:{class:"token attr-value"}},[s("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),t._v("currency"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("i18n-n")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v(":value")]),s("span",{pre:!0,attrs:{class:"token attr-value"}},[s("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),t._v("100"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])]),t._v(" "),s("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v("format")]),s("span",{pre:!0,attrs:{class:"token attr-value"}},[s("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),t._v("currency"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])]),t._v(" "),s("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v("locale")]),s("span",{pre:!0,attrs:{class:"token attr-value"}},[s("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),t._v("ja-JP"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n")])])]),s("p",[t._v("will produce the below output:")]),t._v(" "),s("div",{staticClass:"language-html extra-class"},[s("pre",{pre:!0,attrs:{class:"language-html"}},[s("code",[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("div")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v("id")]),s("span",{pre:!0,attrs:{class:"token attr-value"}},[s("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),t._v("app"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("span")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("100"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("span")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("$100.00"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("span")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("¥100"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n")])])]),s("p",[t._v("But the real power of this component comes into play when it is used with "),s("a",{attrs:{href:"https://vuejs.org/v2/guide/components-slots.html#Scoped-Slots",target:"_blank",rel:"noopener noreferrer"}},[t._v("scoped slots"),s("OutboundLink")],1),t._v(".")]),t._v(" "),s("p",[t._v("Let's say there is a requirement to render the integer part of the number with a bolder font. This can be achieved by specifying "),s("code",[t._v("integer")]),t._v(" scoped slot element:")]),t._v(" "),s("div",{staticClass:"language-html extra-class"},[s("pre",{pre:!0,attrs:{class:"language-html"}},[s("code",[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("i18n-n")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v(":value")]),s("span",{pre:!0,attrs:{class:"token attr-value"}},[s("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),t._v("100"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])]),t._v(" "),s("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v("format")]),s("span",{pre:!0,attrs:{class:"token attr-value"}},[s("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),t._v("currency"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("template")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token attr-name"}},[s("span",{pre:!0,attrs:{class:"token namespace"}},[t._v("v-slot:")]),t._v("integer")]),s("span",{pre:!0,attrs:{class:"token attr-value"}},[s("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),t._v("slotProps"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("span")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token special-attr"}},[s("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v("style")]),s("span",{pre:!0,attrs:{class:"token attr-value"}},[s("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),s("span",{pre:!0,attrs:{class:"token value css language-css"}},[s("span",{pre:!0,attrs:{class:"token property"}},[t._v("font-weight")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(":")]),t._v(" bold")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])])]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("{{ slotProps.integer }}"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n")])])]),s("p",[t._v("Template above will result in the following HTML:")]),t._v(" "),s("div",{staticClass:"language-html extra-class"},[s("pre",{pre:!0,attrs:{class:"language-html"}},[s("code",[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("span")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("$"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("span")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token special-attr"}},[s("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v("style")]),s("span",{pre:!0,attrs:{class:"token attr-value"}},[s("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),s("span",{pre:!0,attrs:{class:"token value css language-css"}},[s("span",{pre:!0,attrs:{class:"token property"}},[t._v("font-weight")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(":")]),t._v(" bold")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])])]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("100"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v(".00"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n")])])]),s("p",[t._v("It is possible to specify multiple scoped slots at the same time:")]),t._v(" "),s("div",{staticClass:"language-html extra-class"},[s("pre",{pre:!0,attrs:{class:"language-html"}},[s("code",[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("i18n-n")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v(":value")]),s("span",{pre:!0,attrs:{class:"token attr-value"}},[s("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),t._v("1234"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])]),t._v(" "),s("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v(":format")]),s("span",{pre:!0,attrs:{class:"token attr-value"}},[s("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),t._v("{ key: "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("'")]),t._v("currency"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("'")]),t._v(", currency: "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("'")]),t._v("EUR"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("'")]),t._v(" }"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("template")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token attr-name"}},[s("span",{pre:!0,attrs:{class:"token namespace"}},[t._v("v-slot:")]),t._v("currency")]),s("span",{pre:!0,attrs:{class:"token attr-value"}},[s("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),t._v("slotProps"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("span")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token special-attr"}},[s("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v("style")]),s("span",{pre:!0,attrs:{class:"token attr-value"}},[s("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),s("span",{pre:!0,attrs:{class:"token value css language-css"}},[s("span",{pre:!0,attrs:{class:"token property"}},[t._v("color")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(":")]),t._v(" green")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])])]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("{{ slotProps.currency }}"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("template")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token attr-name"}},[s("span",{pre:!0,attrs:{class:"token namespace"}},[t._v("v-slot:")]),t._v("integer")]),s("span",{pre:!0,attrs:{class:"token attr-value"}},[s("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),t._v("slotProps"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("span")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token special-attr"}},[s("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v("style")]),s("span",{pre:!0,attrs:{class:"token attr-value"}},[s("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),s("span",{pre:!0,attrs:{class:"token value css language-css"}},[s("span",{pre:!0,attrs:{class:"token property"}},[t._v("font-weight")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(":")]),t._v(" bold")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])])]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("{{ slotProps.integer }}"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("template")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token attr-name"}},[s("span",{pre:!0,attrs:{class:"token namespace"}},[t._v("v-slot:")]),t._v("group")]),s("span",{pre:!0,attrs:{class:"token attr-value"}},[s("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),t._v("slotProps"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("span")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token special-attr"}},[s("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v("style")]),s("span",{pre:!0,attrs:{class:"token attr-value"}},[s("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),s("span",{pre:!0,attrs:{class:"token value css language-css"}},[s("span",{pre:!0,attrs:{class:"token property"}},[t._v("font-weight")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(":")]),t._v(" bold")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])])]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("{{ slotProps.group }}"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("template")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token attr-name"}},[s("span",{pre:!0,attrs:{class:"token namespace"}},[t._v("v-slot:")]),t._v("fraction")]),s("span",{pre:!0,attrs:{class:"token attr-value"}},[s("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),t._v("slotProps"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("span")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token special-attr"}},[s("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v("style")]),s("span",{pre:!0,attrs:{class:"token attr-value"}},[s("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),s("span",{pre:!0,attrs:{class:"token value css language-css"}},[s("span",{pre:!0,attrs:{class:"token property"}},[t._v("font-size")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(":")]),t._v(" small")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])])]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("{{ slotProps.fraction }}"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n")])])]),s("p",[t._v("(this resulting HTML was formatted for better readability)")]),t._v(" "),s("div",{staticClass:"language-html extra-class"},[s("pre",{pre:!0,attrs:{class:"language-html"}},[s("code",[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("span")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("span")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token special-attr"}},[s("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v("style")]),s("span",{pre:!0,attrs:{class:"token attr-value"}},[s("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),s("span",{pre:!0,attrs:{class:"token value css language-css"}},[s("span",{pre:!0,attrs:{class:"token property"}},[t._v("color")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(":")]),t._v(" green")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])])]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("€"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("span")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token special-attr"}},[s("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v("style")]),s("span",{pre:!0,attrs:{class:"token attr-value"}},[s("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),s("span",{pre:!0,attrs:{class:"token value css language-css"}},[s("span",{pre:!0,attrs:{class:"token property"}},[t._v("font-weight")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(":")]),t._v(" bold")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])])]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("1"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("span")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token special-attr"}},[s("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v("style")]),s("span",{pre:!0,attrs:{class:"token attr-value"}},[s("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),s("span",{pre:!0,attrs:{class:"token value css language-css"}},[s("span",{pre:!0,attrs:{class:"token property"}},[t._v("font-weight")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(":")]),t._v(" bold")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])])]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v(","),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("span")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token special-attr"}},[s("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v("style")]),s("span",{pre:!0,attrs:{class:"token attr-value"}},[s("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),s("span",{pre:!0,attrs:{class:"token value css language-css"}},[s("span",{pre:!0,attrs:{class:"token property"}},[t._v("font-weight")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(":")]),t._v(" bold")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])])]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("234"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("span")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token special-attr"}},[s("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v("style")]),s("span",{pre:!0,attrs:{class:"token attr-value"}},[s("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),s("span",{pre:!0,attrs:{class:"token value css language-css"}},[s("span",{pre:!0,attrs:{class:"token property"}},[t._v("font-size")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(":")]),t._v(" small")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])])]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("00"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n")])])]),s("p",[t._v("You can choose the root container's node type by specifying a "),s("code",[t._v("tag")]),t._v(" prop. If omitted, it defaults to "),s("code",[t._v("'span'")]),t._v(". You can also set it to the boolean value "),s("code",[t._v("false")]),t._v(" to insert the child nodes directly without creating a root element.")]),t._v(" "),s("p",[t._v("Full list of the supported scoped slots as well as other "),s("code",[t._v("")]),t._v(" properties can be found "),s("RouterLink",{attrs:{to:"/api/#i18n-n-functional-component"}},[t._v("on API page")]),t._v(".")],1)])}),[],!1,null,null,null);a.default=e.exports}}]); \ No newline at end of file diff --git a/assets/js/22.caf9c8c3.js b/assets/js/22.caf9c8c3.js new file mode 100644 index 000000000..ce728e799 --- /dev/null +++ b/assets/js/22.caf9c8c3.js @@ -0,0 +1 @@ +(window.webpackJsonp=window.webpackJsonp||[]).push([[22],{475:function(t,a,s){"use strict";s.r(a);var n=s(44),p=Object(n.a)({},(function(){var t=this,a=t.$createElement,s=t._self._c||a;return s("ContentSlotsDistributor",{attrs:{"slot-key":t.$parent.slotKey}},[s("h1",{attrs:{id:"pluralization"}},[s("a",{staticClass:"header-anchor",attrs:{href:"#pluralization"}},[t._v("#")]),t._v(" Pluralization")]),t._v(" "),s("p",[t._v("You can translate with pluralization. You must define the locale that have a pipe "),s("code",[t._v("|")]),t._v(" separator, and define plurals in pipe separator.")]),t._v(" "),s("p",[s("em",[t._v("Your template will need to use "),s("code",[t._v("$tc()")]),t._v(" instead of "),s("code",[t._v("$t()")]),t._v(".")])]),t._v(" "),s("p",[t._v("Locale messages below:")]),t._v(" "),s("div",{staticClass:"language-js extra-class"},[s("pre",{pre:!0,attrs:{class:"language-js"}},[s("code",[s("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("const")]),t._v(" messages "),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("en")]),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("car")]),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token string"}},[t._v("'car | cars'")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("apple")]),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token string"}},[t._v("'no apples | one apple | {count} apples'")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n")])])]),s("p",[t._v("Template below:")]),t._v(" "),s("div",{staticClass:"language-html extra-class"},[s("pre",{pre:!0,attrs:{class:"language-html"}},[s("code",[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("p")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("{{ $tc('car', 1) }}"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("p")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("{{ $tc('car', 2) }}"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n\n"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("p")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("{{ $tc('apple', 0) }}"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("p")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("{{ $tc('apple', 1) }}"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("p")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("{{ $tc('apple', 10, { count: 10 }) }}"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n")])])]),s("p",[t._v("Output below:")]),t._v(" "),s("div",{staticClass:"language-html extra-class"},[s("pre",{pre:!0,attrs:{class:"language-html"}},[s("code",[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("p")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("car"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("p")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("cars"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n\n"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("p")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("no apples"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("p")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("one apple"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("p")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("10 apples"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n")])])]),s("h2",{attrs:{id:"accessing-the-number-via-the-pre-defined-argument"}},[s("a",{staticClass:"header-anchor",attrs:{href:"#accessing-the-number-via-the-pre-defined-argument"}},[t._v("#")]),t._v(" Accessing the number via the pre-defined argument")]),t._v(" "),s("p",[t._v("You don't need to explicitly give the number for pluralization.\nThe number can be accessed within locale messages via pre-defined named arguments "),s("code",[t._v("{count}")]),t._v(" and/or "),s("code",[t._v("{n}")]),t._v(".\nYou can overwrite those pre-defined named arguments if necessary.")]),t._v(" "),s("p",[t._v("Locale messages the below:")]),t._v(" "),s("div",{staticClass:"language-js extra-class"},[s("pre",{pre:!0,attrs:{class:"language-js"}},[s("code",[s("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("const")]),t._v(" messages "),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("en")]),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("apple")]),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token string"}},[t._v("'no apples | one apple | {count} apples'")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("banana")]),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token string"}},[t._v("'no bananas | {n} banana | {n} bananas'")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n")])])]),s("p",[t._v("Template below:")]),t._v(" "),s("div",{staticClass:"language-html extra-class"},[s("pre",{pre:!0,attrs:{class:"language-html"}},[s("code",[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("p")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("{{ $tc('apple', 10, { count: 10 }) }}"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("p")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("{{ $tc('apple', 10) }}"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n\n"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("p")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("{{ $tc('banana', 1, { n: 1 }) }}"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("p")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("{{ $tc('banana', 1) }}"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("p")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("{{ $tc('banana', 100, { n: 'too many' }) }}"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n")])])]),s("p",[t._v("Output below:")]),t._v(" "),s("div",{staticClass:"language-html extra-class"},[s("pre",{pre:!0,attrs:{class:"language-html"}},[s("code",[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("p")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("10 apples"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("p")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("10 apples"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n\n"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("p")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("1 banana"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("p")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("1 banana"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("p")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("too many bananas"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n")])])]),s("h2",{attrs:{id:"custom-pluralization"}},[s("a",{staticClass:"header-anchor",attrs:{href:"#custom-pluralization"}},[t._v("#")]),t._v(" Custom pluralization")]),t._v(" "),s("p",[s("em",[t._v("This feature is available since version 8.0")])]),t._v(" "),s("p",[t._v("Such pluralization, however, does not apply to all languages (Slavic languages, for example, have different pluralization rules).")]),t._v(" "),s("p",[t._v("In order to implement these rules you can pass an optional "),s("code",[t._v("pluralizationRules")]),t._v(" object into "),s("code",[t._v("VueI18n")]),t._v(" constructor options.")]),t._v(" "),s("p",[t._v("Very simplified example using rules for Slavic languages (Russian, Ukrainian, etc.):")]),t._v(" "),s("div",{staticClass:"language-js extra-class"},[s("pre",{pre:!0,attrs:{class:"language-js"}},[s("code",[s("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("new")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token class-name"}},[t._v("VueI18n")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// Key - language to use the rule for, `'ru'`, in this case")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// Value - function to choose right plural form")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("pluralizationRules")]),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token comment"}},[t._v("/**\n * @param choice {number} a choice index given by the input to $tc: `$tc('path.to.rule', choiceIndex)`\n * @param choicesLength {number} an overall amount of available choices\n * @returns a final choice index to select plural word by\n */")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token string-property property"}},[t._v("'ru'")]),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("function")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),s("span",{pre:!0,attrs:{class:"token parameter"}},[t._v("choice"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" choicesLength")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// this === VueI18n instance, so the locale property also exists here")]),t._v("\n\n "),s("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("if")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v("choice "),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v("===")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token number"}},[t._v("0")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("return")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token number"}},[t._v("0")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n\n "),s("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("const")]),t._v(" teen "),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" choice "),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v(">")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token number"}},[t._v("10")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v("&&")]),t._v(" choice "),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v("<")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token number"}},[t._v("20")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("const")]),t._v(" endsWithOne "),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" choice "),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v("%")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token number"}},[t._v("10")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v("===")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token number"}},[t._v("1")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n\n "),s("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("if")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v("choicesLength "),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v("<")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token number"}},[t._v("4")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("return")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v("!")]),t._v("teen "),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v("&&")]),t._v(" endsWithOne"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v("?")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token number"}},[t._v("1")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token number"}},[t._v("2")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("if")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v("!")]),t._v("teen "),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v("&&")]),t._v(" endsWithOne"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("return")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token number"}},[t._v("1")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("if")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v("!")]),t._v("teen "),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v("&&")]),t._v(" choice "),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v("%")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token number"}},[t._v("10")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v(">=")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token number"}},[t._v("2")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v("&&")]),t._v(" choice "),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v("%")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token number"}},[t._v("10")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v("<=")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token number"}},[t._v("4")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("return")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token number"}},[t._v("2")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n\n "),s("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("return")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v("choicesLength "),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v("<")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token number"}},[t._v("4")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v("?")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token number"}},[t._v("2")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token number"}},[t._v("3")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v("\n")])])]),s("p",[t._v("This would effectively give this:")]),t._v(" "),s("div",{staticClass:"language-javascript extra-class"},[s("pre",{pre:!0,attrs:{class:"language-javascript"}},[s("code",[s("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("const")]),t._v(" messages "),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("ru")]),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("car")]),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token string"}},[t._v("'0 машин | {n} машина | {n} машины | {n} машин'")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("banana")]),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token string"}},[t._v("'нет бананов | {n} банан | {n} банана | {n} бананов'")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n")])])]),s("p",[t._v("Where the format is "),s("code",[t._v("0 things | things count ends with 1 | things count ends with 2-4 | things count ends with 5-9, 0 and teens (10-19)")]),t._v(".\nP.S. Slavic pluralization is difficult, you can read more about it "),s("a",{attrs:{href:"http://www.russianlessons.net/lessons/lesson11_main.php",target:"_blank",rel:"noopener noreferrer"}},[t._v("here"),s("OutboundLink")],1),t._v(".")]),t._v(" "),s("p",[t._v("Your template still needs to use "),s("code",[t._v("$tc()")]),t._v(", not "),s("code",[t._v("$t()")]),t._v(":")]),t._v(" "),s("div",{staticClass:"language-html extra-class"},[s("pre",{pre:!0,attrs:{class:"language-html"}},[s("code",[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("p")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("{{ $tc('car', 1) }}"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("p")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("{{ $tc('car', 2) }}"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("p")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("{{ $tc('car', 4) }}"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("p")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("{{ $tc('car', 12) }}"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("p")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("{{ $tc('car', 21) }}"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n\n"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("p")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("{{ $tc('banana', 0) }}"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("p")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("{{ $tc('banana', 4) }}"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("p")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("{{ $tc('banana', 11) }}"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("p")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("{{ $tc('banana', 31) }}"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n")])])]),s("p",[t._v("Which results in:")]),t._v(" "),s("div",{staticClass:"language-html extra-class"},[s("pre",{pre:!0,attrs:{class:"language-html"}},[s("code",[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("p")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("1 машина"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("p")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("2 машины"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("p")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("4 машины"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("p")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("12 машин"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("p")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("21 машина"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n\n"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("p")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("нет бананов"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("p")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("4 банана"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("p")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("11 бананов"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("p")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("31 банан"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n")])])]),s("h3",{attrs:{id:"default-pluralization"}},[s("a",{staticClass:"header-anchor",attrs:{href:"#default-pluralization"}},[t._v("#")]),t._v(" Default pluralization")]),t._v(" "),s("p",[t._v("If your current locale is not found in a pluralization map, the "),s("a",{attrs:{href:"#pluralization"}},[t._v("default")]),t._v(" rule of the english language will be used.")])])}),[],!1,null,null,null);a.default=p.exports}}]); \ No newline at end of file diff --git a/assets/js/23.78943b5d.js b/assets/js/23.78943b5d.js new file mode 100644 index 000000000..2b5c01bb8 --- /dev/null +++ b/assets/js/23.78943b5d.js @@ -0,0 +1 @@ +(window.webpackJsonp=window.webpackJsonp||[]).push([[23],{473:function(t,s,a){"use strict";a.r(s);var n=a(44),e=Object(n.a)({},(function(){var t=this,s=t.$createElement,a=t._self._c||s;return a("ContentSlotsDistributor",{attrs:{"slot-key":t.$parent.slotKey}},[a("h1",{attrs:{id:"single-file-components"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#single-file-components"}},[t._v("#")]),t._v(" Single file components")]),t._v(" "),a("h2",{attrs:{id:"basic-usage"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#basic-usage"}},[t._v("#")]),t._v(" Basic Usage")]),t._v(" "),a("p",[t._v("If you are building Vue component or Vue application using single file components, you can manage the locale messages "),a("code",[t._v("i18n")]),t._v(" custom block.")]),t._v(" "),a("p",[t._v("The following in "),a("a",{attrs:{href:"https://github.com/kazupon/vue-i18n/tree/dev/examples/sfc",target:"_blank",rel:"noopener noreferrer"}},[t._v("single file components example"),a("OutboundLink")],1),t._v(":")]),t._v(" "),a("div",{staticClass:"language-vue extra-class"},[a("pre",{pre:!0,attrs:{class:"language-vue"}},[a("code",[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("i18n")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v('\n{\n "en": {\n "hello": "hello world!"\n },\n "ja": {\n "hello": "こんにちは、世界!"\n }\n}\n'),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n\n"),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("template")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("div")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v("id")]),a("span",{pre:!0,attrs:{class:"token attr-value"}},[a("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),t._v("app"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("label")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v("for")]),a("span",{pre:!0,attrs:{class:"token attr-value"}},[a("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),t._v("locale"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("locale"),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("select")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v("v-model")]),a("span",{pre:!0,attrs:{class:"token attr-value"}},[a("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),t._v("locale"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("option")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("en"),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("option")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("ja"),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("p")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("message: {{ $t('hello') }}"),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n"),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n\n"),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("script")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),a("span",{pre:!0,attrs:{class:"token script"}},[a("span",{pre:!0,attrs:{class:"token language-javascript"}},[t._v("\n"),a("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("export")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("default")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("name")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v("'app'")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token function"}},[t._v("data")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("this")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("$i18n"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("locale "),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v("'en'")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("return")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("locale")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v("'en'")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("watch")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token function"}},[t._v("locale")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),a("span",{pre:!0,attrs:{class:"token parameter"}},[t._v("val")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("this")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("$i18n"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("locale "),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" val\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n")])]),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n")])])]),a("h2",{attrs:{id:"installing-vue-i18n-loader"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#installing-vue-i18n-loader"}},[t._v("#")]),t._v(" Installing vue-i18n-loader")]),t._v(" "),a("p",[t._v("You need to install "),a("code",[t._v("vue-loader")]),t._v(" and "),a("code",[t._v("vue-i18n-loader")]),t._v(" to use "),a("code",[t._v("")]),t._v(" custom blocks. While "),a("a",{attrs:{href:"https://github.com/vuejs/vue-loader",target:"_blank",rel:"noopener noreferrer"}},[t._v("vue-loader"),a("OutboundLink")],1),t._v(" most likely is already used in your project if you are working with single file components, you must install "),a("a",{attrs:{href:"https://github.com/kazupon/vue-i18n-loader",target:"_blank",rel:"noopener noreferrer"}},[t._v("vue-i18n-loader"),a("OutboundLink")],1),t._v(" additionally:")]),t._v(" "),a("div",{staticClass:"language-sh extra-class"},[a("pre",{pre:!0,attrs:{class:"language-sh"}},[a("code",[a("span",{pre:!0,attrs:{class:"token function"}},[t._v("npm")]),t._v(" i --save-dev @intlify/vue-i18n-loader\n")])])]),a("h2",{attrs:{id:"webpack"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#webpack"}},[t._v("#")]),t._v(" Webpack")]),t._v(" "),a("p",[t._v("For Webpack the configuration below is required:")]),t._v(" "),a("p",[t._v("for vue-loader v15 or later:")]),t._v(" "),a("div",{staticClass:"language-js extra-class"},[a("pre",{pre:!0,attrs:{class:"language-js"}},[a("code",[t._v("module"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("exports "),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// ...")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("module")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("rules")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("[")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("test")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token regex"}},[a("span",{pre:!0,attrs:{class:"token regex-delimiter"}},[t._v("/")]),a("span",{pre:!0,attrs:{class:"token regex-source language-regex"}},[t._v("\\.vue$")]),a("span",{pre:!0,attrs:{class:"token regex-delimiter"}},[t._v("/")])]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("loader")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v("'vue-loader'")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("resourceQuery")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token regex"}},[a("span",{pre:!0,attrs:{class:"token regex-delimiter"}},[t._v("/")]),a("span",{pre:!0,attrs:{class:"token regex-source language-regex"}},[t._v("blockType=i18n")]),a("span",{pre:!0,attrs:{class:"token regex-delimiter"}},[t._v("/")])]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("type")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v("'javascript/auto'")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("loader")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v("'@intlify/vue-i18n-loader'")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// ...")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("]")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// ...")]),t._v("\n"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n")])])]),a("p",[t._v("for vue-loader v14:")]),t._v(" "),a("div",{staticClass:"language-js extra-class"},[a("pre",{pre:!0,attrs:{class:"language-js"}},[a("code",[t._v("module"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("exports "),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// ...")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("module")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("rules")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("[")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("test")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token regex"}},[a("span",{pre:!0,attrs:{class:"token regex-delimiter"}},[t._v("/")]),a("span",{pre:!0,attrs:{class:"token regex-source language-regex"}},[t._v("\\.vue$")]),a("span",{pre:!0,attrs:{class:"token regex-delimiter"}},[t._v("/")])]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("loader")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v("'vue-loader'")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("options")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("loaders")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// you need to specify `i18n` loaders key with `vue-i18n-loader` (https://github.com/intlify/vue-i18n-loader)")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("i18n")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v("'@intlify/vue-i18n-loader'")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// ...")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("]")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// ...")]),t._v("\n"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n")])])]),a("h2",{attrs:{id:"vue-cli-3-0"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#vue-cli-3-0"}},[t._v("#")]),t._v(" Vue CLI 3.0")]),t._v(" "),a("p",[a("a",{attrs:{href:"https://github.com/vuejs/vue-cli",target:"_blank",rel:"noopener noreferrer"}},[t._v("Vue CLI 3.0"),a("OutboundLink")],1),t._v(" hides the webpack configuration, so, if we want to add support to the "),a("code",[t._v("")]),t._v(" tag inside a single file component we need to modify the existing configuration.")]),t._v(" "),a("p",[t._v("In order to do that we have to create a "),a("code",[t._v("vue.config.js")]),t._v(" at the root of our project. Once we have done that, we have to include the following:")]),t._v(" "),a("p",[t._v("for vue-loader v15 or later:")]),t._v(" "),a("div",{staticClass:"language-js extra-class"},[a("pre",{pre:!0,attrs:{class:"language-js"}},[a("code",[t._v("module"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("exports "),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token function-variable function"}},[t._v("chainWebpack")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token parameter"}},[t._v("config")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=>")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n config"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("module\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),a("span",{pre:!0,attrs:{class:"token function"}},[t._v("rule")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),a("span",{pre:!0,attrs:{class:"token string"}},[t._v('"i18n"')]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),a("span",{pre:!0,attrs:{class:"token function"}},[t._v("resourceQuery")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),a("span",{pre:!0,attrs:{class:"token regex"}},[a("span",{pre:!0,attrs:{class:"token regex-delimiter"}},[t._v("/")]),a("span",{pre:!0,attrs:{class:"token regex-source language-regex"}},[t._v("blockType=i18n")]),a("span",{pre:!0,attrs:{class:"token regex-delimiter"}},[t._v("/")])]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),a("span",{pre:!0,attrs:{class:"token function"}},[t._v("type")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),a("span",{pre:!0,attrs:{class:"token string"}},[t._v("'javascript/auto'")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),a("span",{pre:!0,attrs:{class:"token function"}},[t._v("use")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),a("span",{pre:!0,attrs:{class:"token string"}},[t._v('"i18n"')]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),a("span",{pre:!0,attrs:{class:"token function"}},[t._v("loader")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),a("span",{pre:!0,attrs:{class:"token string"}},[t._v('"@intlify/vue-i18n-loader"')]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),a("span",{pre:!0,attrs:{class:"token function"}},[t._v("end")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n")])])]),a("p",[t._v("for vue-loader v14:")]),t._v(" "),a("div",{staticClass:"language-js extra-class"},[a("pre",{pre:!0,attrs:{class:"language-js"}},[a("code",[a("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("const")]),t._v(" merge "),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token function"}},[t._v("require")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),a("span",{pre:!0,attrs:{class:"token string"}},[t._v("'deepmerge'")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v("\n\nmodule"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("exports "),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token function-variable function"}},[t._v("chainWebpack")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token parameter"}},[t._v("config")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=>")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n config"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("module\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),a("span",{pre:!0,attrs:{class:"token function"}},[t._v("rule")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),a("span",{pre:!0,attrs:{class:"token string"}},[t._v("'vue'")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),a("span",{pre:!0,attrs:{class:"token function"}},[t._v("use")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),a("span",{pre:!0,attrs:{class:"token string"}},[t._v("'vue-loader'")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),a("span",{pre:!0,attrs:{class:"token function"}},[t._v("tap")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),a("span",{pre:!0,attrs:{class:"token parameter"}},[t._v("options")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=>")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token function"}},[t._v("merge")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v("options"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("loaders")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("i18n")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v("'@intlify/vue-i18n-loader'")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n")])])]),a("p",[a("em",[t._v("Don 't forget to install "),a("a",{attrs:{href:"https://github.com/KyleAMathews/deepmerge",target:"_blank",rel:"noopener noreferrer"}},[t._v("deepmerge"),a("OutboundLink")],1),t._v("! ("),a("code",[t._v("npm i deepmerge -D")]),t._v(" or "),a("code",[t._v("yarn add deepmerge -D")]),t._v(")")])]),t._v(" "),a("p",[t._v("If you want to read more about modifying the existing configuration "),a("a",{attrs:{href:"https://cli.vuejs.org/guide/webpack.html",target:"_blank",rel:"noopener noreferrer"}},[t._v("click here"),a("OutboundLink")],1),t._v(".")]),t._v(" "),a("h2",{attrs:{id:"laravel-mix"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#laravel-mix"}},[t._v("#")]),t._v(" Laravel-Mix")]),t._v(" "),a("p",[t._v("for Laravel-mix 4 with vue-loader v15 or later:")]),t._v(" "),a("div",{staticClass:"language-js extra-class"},[a("pre",{pre:!0,attrs:{class:"language-js"}},[a("code",[a("span",{pre:!0,attrs:{class:"token comment"}},[t._v('// Extend Mix with the "i18n" method, that loads the vue-i18n-loader')]),t._v("\nmix"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),a("span",{pre:!0,attrs:{class:"token function"}},[t._v("extend")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v("'i18n'")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("new")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token class-name"}},[t._v("class")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token function"}},[t._v("webpackRules")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("return")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("[")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("resourceQuery")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token regex"}},[a("span",{pre:!0,attrs:{class:"token regex-delimiter"}},[t._v("/")]),a("span",{pre:!0,attrs:{class:"token regex-source language-regex"}},[t._v("blockType=i18n")]),a("span",{pre:!0,attrs:{class:"token regex-delimiter"}},[t._v("/")])]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("type")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v("'javascript/auto'")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("loader")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v("'@intlify/vue-i18n-loader'")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("]")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n\n"),a("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// Make sure to call the .i18n() (to load the loader) before .js(..., ...)")]),t._v("\nmix"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),a("span",{pre:!0,attrs:{class:"token function"}},[t._v("i18n")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),a("span",{pre:!0,attrs:{class:"token function"}},[t._v("js")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v("'resources/js/App.js'")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v("'public/js/app.js'")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v("...")]),t._v("\n")])])]),a("p",[t._v("for Laravel-mix 2 with vue-loader v14:")]),t._v(" "),a("p",[t._v("As of "),a("a",{attrs:{href:"https://github.com/JeffreyWay/laravel-mix/releases/tag/v2.1",target:"_blank",rel:"noopener noreferrer"}},[t._v("V2.1"),a("OutboundLink")],1),t._v(" of Laravel-mix, you can add custom rules via mix.extend(). Laravel mix already has its own rules for handling .vue files. To add the "),a("code",[t._v("vue-i18n-loader")]),t._v(", add the following to "),a("code",[t._v("webpack.mix.js")])]),t._v(" "),a("div",{staticClass:"language-js extra-class"},[a("pre",{pre:!0,attrs:{class:"language-js"}},[a("code",[a("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// The below code will inject i18n Kazupon/vue-18-loader as a loader for .vue files.")]),t._v("\nmix"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),a("span",{pre:!0,attrs:{class:"token function"}},[t._v("extend")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v("'i18n'")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("function")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token parameter"}},[t._v("webpackConfig"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v("...")]),t._v("args")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n webpackConfig"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("module"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("rules"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),a("span",{pre:!0,attrs:{class:"token function"}},[t._v("forEach")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token parameter"}},[t._v("module")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=>")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token comment"}},[t._v('// Search for the "vue-loader" component, which handles .vue files.')]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("if")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v(" module"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("loader "),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v("!==")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v("'vue-loader'")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("return")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n\n "),a("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// Within this module, add the vue-i18n-loader for the i18n tag.")]),t._v("\n module"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("options"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("loaders"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("i18n "),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v("'@intlify/vue-i18n-loader'")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n\n"),a("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// Make sure to call .i18n() before .js(..., ...)")]),t._v("\nmix"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),a("span",{pre:!0,attrs:{class:"token function"}},[t._v("i18n")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),a("span",{pre:!0,attrs:{class:"token function"}},[t._v("js")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v("'resources/assets/js/App.js'")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v("'public/js/app.js'")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v("...")]),t._v("\n")])])]),a("h2",{attrs:{id:"yaml-loading"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#yaml-loading"}},[t._v("#")]),t._v(" YAML loading")]),t._v(" "),a("p",[a("code",[t._v("i18n")]),t._v(" custom blocks need to specify "),a("code",[t._v("JSON")]),t._v(" format, also you can use "),a("code",[t._v("YAML")]),t._v(" format by using pre-loader feature of "),a("code",[t._v("vue-loader")]),t._v(".")]),t._v(" "),a("p",[t._v("the "),a("code",[t._v("i18n")]),t._v(" custom blocks below of "),a("code",[t._v("YAML")]),t._v(" format:")]),t._v(" "),a("div",{staticClass:"language-vue extra-class"},[a("pre",{pre:!0,attrs:{class:"language-vue"}},[a("code",[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("i18n")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v('\nen:\n hello: "hello world!"\nja:\n hello: "こんにちは、世界!"\n'),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n")])])]),a("p",[t._v("Webpack conf the below:")]),t._v(" "),a("p",[t._v("for vue-loader v15 or later:")]),t._v(" "),a("div",{staticClass:"language-js extra-class"},[a("pre",{pre:!0,attrs:{class:"language-js"}},[a("code",[a("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// Vue CLI 3.0")]),t._v("\nmodule"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("exports "),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token function-variable function"}},[t._v("chainWebpack")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token parameter"}},[t._v("config")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=>")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n config"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("module\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),a("span",{pre:!0,attrs:{class:"token function"}},[t._v("rule")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),a("span",{pre:!0,attrs:{class:"token string"}},[t._v('"i18n"')]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),a("span",{pre:!0,attrs:{class:"token function"}},[t._v("resourceQuery")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),a("span",{pre:!0,attrs:{class:"token regex"}},[a("span",{pre:!0,attrs:{class:"token regex-delimiter"}},[t._v("/")]),a("span",{pre:!0,attrs:{class:"token regex-source language-regex"}},[t._v("blockType=i18n")]),a("span",{pre:!0,attrs:{class:"token regex-delimiter"}},[t._v("/")])]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),a("span",{pre:!0,attrs:{class:"token function"}},[t._v("type")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),a("span",{pre:!0,attrs:{class:"token string"}},[t._v("'javascript/auto'")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),a("span",{pre:!0,attrs:{class:"token function"}},[t._v("use")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),a("span",{pre:!0,attrs:{class:"token string"}},[t._v('"i18n"')]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),a("span",{pre:!0,attrs:{class:"token function"}},[t._v("loader")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),a("span",{pre:!0,attrs:{class:"token string"}},[t._v('"@intlify/vue-i18n-loader"')]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),a("span",{pre:!0,attrs:{class:"token function"}},[t._v("end")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),a("span",{pre:!0,attrs:{class:"token function"}},[t._v("use")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),a("span",{pre:!0,attrs:{class:"token string"}},[t._v("'yaml'")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),a("span",{pre:!0,attrs:{class:"token function"}},[t._v("loader")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),a("span",{pre:!0,attrs:{class:"token string"}},[t._v("'yaml-loader'")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),a("span",{pre:!0,attrs:{class:"token function"}},[t._v("end")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n")])])]),a("p",[t._v("for vue-loader v14:")]),t._v(" "),a("div",{staticClass:"language-js extra-class"},[a("pre",{pre:!0,attrs:{class:"language-js"}},[a("code",[t._v("module"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("exports "),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// ...")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("module")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("rules")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("[")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("test")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token regex"}},[a("span",{pre:!0,attrs:{class:"token regex-delimiter"}},[t._v("/")]),a("span",{pre:!0,attrs:{class:"token regex-source language-regex"}},[t._v("\\.vue$")]),a("span",{pre:!0,attrs:{class:"token regex-delimiter"}},[t._v("/")])]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("loader")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v("'vue-loader'")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("options")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("preLoaders")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("i18n")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v("'yaml-loader'")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("loaders")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token literal-property property"}},[t._v("i18n")]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v("'@intlify/vue-i18n-loader'")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// ...")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("]")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token comment"}},[t._v("// ...")]),t._v("\n"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n")])])]),a("h2",{attrs:{id:"multiple-custom-blocks"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#multiple-custom-blocks"}},[t._v("#")]),t._v(" Multiple custom blocks")]),t._v(" "),a("p",[t._v("You can use locale messages with multiple "),a("code",[t._v("i18n")]),t._v(" custom blocks.")]),t._v(" "),a("div",{staticClass:"language-vue extra-class"},[a("pre",{pre:!0,attrs:{class:"language-vue"}},[a("code",[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("i18n")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v("src")]),a("span",{pre:!0,attrs:{class:"token attr-value"}},[a("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),t._v("./common/locales.json"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n"),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("i18n")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v('\n {\n "en": {\n "hello": "hello world!"\n },\n "ja": {\n "hello": "こんにちは、世界!"\n }\n }\n'),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n")])])]),a("p",[t._v("In the above, first custom block load the common locale message with "),a("code",[t._v("src")]),t._v(" attribute, second custom block load the locale message that is defined only at single file component. These locale messages will be merged as locale message of component.")]),t._v(" "),a("p",[t._v("In this way, multiple custom blocks useful when want to be used as module.")]),t._v(" "),a("h2",{attrs:{id:"scoped-style"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#scoped-style"}},[t._v("#")]),t._v(" Scoped style")]),t._v(" "),a("p",[t._v("When using "),a("code",[t._v("vue-i18n")]),t._v(" with "),a("code",[t._v("scoped style")]),t._v(", it's important to remember to use a "),a("a",{attrs:{href:"https://vue-loader.vuejs.org/guide/scoped-css.html#child-component-root-elements",target:"_blank",rel:"noopener noreferrer"}},[t._v("deep selector"),a("OutboundLink")],1),t._v(" for styling an element "),a("strong",[a("em",[t._v("inside")])]),t._v(" the translation string. For example:")]),t._v(" "),a("p",[a("strong",[t._v("Translation contains only text")]),t._v(" (Work without deep selector)")]),t._v(" "),a("div",{staticClass:"language-vue extra-class"},[a("pre",{pre:!0,attrs:{class:"language-vue"}},[a("code",[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("i18n")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v('\n{\n "en": {\n "hello": "hello world!"\n },\n "ja": {\n "hello": "こんにちは、世界"\n }\n}\n'),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n\n"),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("template")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("div")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v("class")]),a("span",{pre:!0,attrs:{class:"token attr-value"}},[a("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),t._v("parent"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("p")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("message: {{ $t('hello') }}"),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n"),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n\n"),a("span",{pre:!0,attrs:{class:"token comment"}},[t._v("\x3c!-- Will work --\x3e")]),t._v("\n"),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("style")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v("scoped")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),a("span",{pre:!0,attrs:{class:"token style"}},[a("span",{pre:!0,attrs:{class:"token language-css"}},[t._v("\n "),a("span",{pre:!0,attrs:{class:"token selector"}},[t._v(".parent p")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token property"}},[t._v("color")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(":")]),t._v(" #42b883"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n")])]),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n")])])]),a("p",[a("strong",[t._v("Translation with HTML element")]),t._v(" (Must use deep selector)")]),t._v(" "),a("div",{staticClass:"language-vue extra-class"},[a("pre",{pre:!0,attrs:{class:"language-vue"}},[a("code",[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("i18n")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v('\n{\n "en": {\n "hello": "hello'),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("span")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("world!"),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v('"\n },\n "ja": {\n "hello": "こんにちは、'),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("span")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("世界!"),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v('"\n }\n}\n'),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n\n"),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("template")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("div")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v("class")]),a("span",{pre:!0,attrs:{class:"token attr-value"}},[a("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),t._v("parent"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("p")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v("v-html")]),a("span",{pre:!0,attrs:{class:"token attr-value"}},[a("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),t._v("$t("),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("'")]),t._v("hello"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("'")]),t._v(")"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n"),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n\n"),a("span",{pre:!0,attrs:{class:"token comment"}},[t._v("\x3c!-- Won't work --\x3e")]),t._v("\n"),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("style")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v("scoped")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),a("span",{pre:!0,attrs:{class:"token style"}},[a("span",{pre:!0,attrs:{class:"token language-css"}},[t._v("\n "),a("span",{pre:!0,attrs:{class:"token selector"}},[t._v(".parent p")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token property"}},[t._v("color")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(":")]),t._v(" #42b883"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n\n "),a("span",{pre:!0,attrs:{class:"token selector"}},[t._v(".parent p span")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token property"}},[t._v("color")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(":")]),t._v(" red"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n")])]),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n\n"),a("span",{pre:!0,attrs:{class:"token comment"}},[t._v("\x3c!-- Will work >>> --\x3e")]),t._v("\n"),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("style")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v("scoped")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),a("span",{pre:!0,attrs:{class:"token style"}},[a("span",{pre:!0,attrs:{class:"token language-css"}},[t._v("\n "),a("span",{pre:!0,attrs:{class:"token selector"}},[t._v(".parent p")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token property"}},[t._v("color")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(":")]),t._v(" #42b883"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n\n "),a("span",{pre:!0,attrs:{class:"token selector"}},[t._v(".parent p >>> span")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token property"}},[t._v("color")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(":")]),t._v(" red"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n")])]),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n\n"),a("span",{pre:!0,attrs:{class:"token comment"}},[t._v("\x3c!-- Will work /deep/ --\x3e")]),t._v("\n"),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("style")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v("scoped")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),a("span",{pre:!0,attrs:{class:"token style"}},[a("span",{pre:!0,attrs:{class:"token language-css"}},[t._v("\n "),a("span",{pre:!0,attrs:{class:"token selector"}},[t._v(".parent p")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token property"}},[t._v("color")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(":")]),t._v(" #42b883"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n\n "),a("span",{pre:!0,attrs:{class:"token selector"}},[t._v(".parent p /deep/ span")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token property"}},[t._v("color")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(":")]),t._v(" red"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n")])]),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n\n"),a("span",{pre:!0,attrs:{class:"token comment"}},[t._v("\x3c!-- Will work ::v-deep --\x3e")]),t._v("\n"),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("style")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v("scoped")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),a("span",{pre:!0,attrs:{class:"token style"}},[a("span",{pre:!0,attrs:{class:"token language-css"}},[t._v("\n "),a("span",{pre:!0,attrs:{class:"token selector"}},[t._v(".parent p")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token property"}},[t._v("color")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(":")]),t._v(" #42b883"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n\n "),a("span",{pre:!0,attrs:{class:"token selector"}},[t._v("::v-deep .parent p span")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token property"}},[t._v("color")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(":")]),t._v(" red"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(";")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n")])]),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n")])])]),a("h2",{attrs:{id:"custom-blocks-in-functional-component"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#custom-blocks-in-functional-component"}},[t._v("#")]),t._v(" Custom blocks in functional component")]),t._v(" "),a("p",[t._v("If the single file components have the template using a functional component, and you had been defined "),a("code",[t._v("i18n")]),t._v(" custom blocks, note you cannot localize using locale messages.")]),t._v(" "),a("p",[t._v("For example, the following code cannot localize with the locale message of "),a("code",[t._v("i18n")]),t._v(" custom block.")]),t._v(" "),a("div",{staticClass:"language-vue extra-class"},[a("pre",{pre:!0,attrs:{class:"language-vue"}},[a("code",[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("i18n")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v('\n{\n "en": {\n "hello": "hello world"\n },\n "ja": {\n "hello": "こんにちは、世界"\n }\n}\n'),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n\n"),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("template")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v("functional")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token comment"}},[t._v("\x3c!-- 'hello' of locale messages of parent instance --\x3e")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("p")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),t._v("{{ parent.$t('hello') }}"),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n"),a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token tag"}},[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n")])])])])}),[],!1,null,null,null);s.default=e.exports}}]); \ No newline at end of file diff --git a/assets/js/24.984dce40.js b/assets/js/24.984dce40.js new file mode 100644 index 000000000..f0ef0a10c --- /dev/null +++ b/assets/js/24.984dce40.js @@ -0,0 +1 @@ +(window.webpackJsonp=window.webpackJsonp||[]).push([[24],{474:function(e,t,n){"use strict";n.r(t);var i=n(44),a=Object(i.a)({},(function(){var e=this,t=e.$createElement,n=e._self._c||t;return n("ContentSlotsDistributor",{attrs:{"slot-key":e.$parent.slotKey}},[n("h1",{attrs:{id:"tooling"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#tooling"}},[e._v("#")]),e._v(" Tooling")]),e._v(" "),n("p",[e._v("To support the i18n of Vue applications, some tools are officially provided.")]),e._v(" "),n("p",[e._v("There are also tools from third vendors integrating Vue I18n.")]),e._v(" "),n("h2",{attrs:{id:"official-tooling"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#official-tooling"}},[e._v("#")]),e._v(" Official tooling")]),e._v(" "),n("h3",{attrs:{id:"vue-cli-plugin"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#vue-cli-plugin"}},[e._v("#")]),e._v(" Vue CLI Plugin")]),e._v(" "),n("p",[n("a",{attrs:{href:"https://github.com/kazupon/vue-cli-plugin-i18n",target:"_blank",rel:"noopener noreferrer"}},[e._v("vue-cli-plugin-i18n"),n("OutboundLink")],1),e._v(" is officially provided as the Vue CLI Plugin.")]),e._v(" "),n("p",[e._v("With this plugin, you can setup the i18n environment for the Vue application, and support the i18n development environment.")]),e._v(" "),n("h3",{attrs:{id:"nuxt-module"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#nuxt-module"}},[e._v("#")]),e._v(" Nuxt Module")]),e._v(" "),n("p",[n("a",{attrs:{href:"https://github.com/nuxt-community/nuxt-i18n/",target:"_blank",rel:"noopener noreferrer"}},[e._v("nuxt-i18n"),n("OutboundLink")],1),e._v(" is corresponding Nuxt.js module.")]),e._v(" "),n("h3",{attrs:{id:"webpack-loader"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#webpack-loader"}},[e._v("#")]),e._v(" Webpack loader")]),e._v(" "),n("p",[n("a",{attrs:{href:"https://github.com/kazupon/vue-i18n-loader",target:"_blank",rel:"noopener noreferrer"}},[e._v("vue-i18n-loader"),n("OutboundLink")],1),e._v(" is an officially provided webpack loader.")]),e._v(" "),n("p",[e._v("With this loader, you can use the "),n("code",[e._v("i18n")]),e._v(" custom block in the Single file components.")]),e._v(" "),n("p",[e._v("In about "),n("code",[e._v("i18n")]),e._v(" custom block, see the "),n("RouterLink",{attrs:{to:"/guide/sfc.html"}},[e._v("Single file components section")])],1),e._v(" "),n("h3",{attrs:{id:"eslint-plugin"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#eslint-plugin"}},[e._v("#")]),e._v(" ESLint Plugin")]),e._v(" "),n("p",[n("a",{attrs:{href:"https://intlify.github.io/eslint-plugin-vue-i18n/",target:"_blank",rel:"noopener noreferrer"}},[e._v("eslint-plugin-vue-i18n"),n("OutboundLink")],1),e._v(" is ESLint plugin for Vue I18n.")]),e._v(" "),n("p",[e._v("It easily integrates some localization lint features to your Vue.js Application.")]),e._v(" "),n("h3",{attrs:{id:"extensions"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#extensions"}},[e._v("#")]),e._v(" Extensions")]),e._v(" "),n("p",[n("a",{attrs:{href:"https://github.com/kazupon/vue-i18n-extensions",target:"_blank",rel:"noopener noreferrer"}},[e._v("vue-i18n-extensions"),n("OutboundLink")],1),e._v(" provides some extensions for Vue I18n.")]),e._v(" "),n("p",[e._v("You can use this extension to enable SSR and improve i18n performance.")]),e._v(" "),n("h2",{attrs:{id:"_3rd-party-tooling"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#_3rd-party-tooling"}},[e._v("#")]),e._v(" 3rd party tooling")]),e._v(" "),n("h3",{attrs:{id:"babeledit"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#babeledit"}},[e._v("#")]),e._v(" BabelEdit")]),e._v(" "),n("p",[n("a",{attrs:{href:"https://www.codeandweb.com/babeledit",target:"_blank",rel:"noopener noreferrer"}},[e._v("BabelEdit"),n("OutboundLink")],1),e._v(" is translation editor for web apps.")]),e._v(" "),n("p",[e._v("BabelEdit can translate "),n("code",[e._v("json")]),e._v(" files, and it can also translate "),n("code",[e._v("i18n")]),e._v(" custom block of Single-file components.")]),e._v(" "),n("p",[e._v("Read more about BabelEdit in "),n("a",{attrs:{href:"https://www.codeandweb.com/babeledit/tutorials/how-to-translate-your-vue-app-with-vue-i18n",target:"_blank",rel:"noopener noreferrer"}},[e._v("tutorial page"),n("OutboundLink")],1),e._v(".")]),e._v(" "),n("h3",{attrs:{id:"i18n-ally"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#i18n-ally"}},[e._v("#")]),e._v(" i18n Ally")]),e._v(" "),n("p",[n("a",{attrs:{href:"https://marketplace.visualstudio.com/items?itemName=lokalise.i18n-ally",target:"_blank",rel:"noopener noreferrer"}},[e._v("i18n Ally"),n("OutboundLink")],1),e._v(" is i18n extension for VSCode.")]),e._v(" "),n("p",[e._v("i18n Ally give awesome DX for your i18n development.")]),e._v(" "),n("p",[e._v("Read more about i18n Ally in "),n("a",{attrs:{href:"https://github.com/lokalise/i18n-ally/blob/main/README.md",target:"_blank",rel:"noopener noreferrer"}},[e._v("README"),n("OutboundLink")],1),e._v(".")]),e._v(" "),n("h3",{attrs:{id:"i18nplugin-intellij-platform"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#i18nplugin-intellij-platform"}},[e._v("#")]),e._v(" i18nPlugin (intellij platform)")]),e._v(" "),n("p",[n("a",{attrs:{href:"https://github.com/nyavro/i18nPlugin",target:"_blank",rel:"noopener noreferrer"}},[e._v("i18nPlugin"),n("OutboundLink")],1),e._v(" Intellij idea i18next support plugin ( "),n("a",{attrs:{href:"https://plugins.jetbrains.com/plugin/12981-i18n-support",target:"_blank",rel:"noopener noreferrer"}},[e._v("Jetbrains plugin page "),n("OutboundLink")],1),e._v(").")]),e._v(" "),n("p",[e._v('Plugin for i18n typescript/javascript/PHP. Supports vue-i18n. To enable vue-i18n support go to settings -> Tools -> i18n Plugin configuration and check "Vue-i18n". You need set vue locales directory (locales by default).')]),e._v(" "),n("h3",{attrs:{id:"vue-i18n-extract"}},[n("a",{staticClass:"header-anchor",attrs:{href:"#vue-i18n-extract"}},[e._v("#")]),e._v(" vue-i18n-extract")]),e._v(" "),n("p",[n("a",{attrs:{href:"https://github.com/pixari/vue-i18n-extract",target:"_blank",rel:"noopener noreferrer"}},[e._v("vue-i18n-extract"),n("OutboundLink")],1),e._v(" performs static analysis on a Vue.js project based on vue-i18n and reports the following information:")]),e._v(" "),n("ul",[n("li",[e._v("list of all the "),n("strong",[e._v("unused vue-i18n keys")]),e._v(" (entries found in the language files but not used in the project)")]),e._v(" "),n("li",[e._v("list of all the "),n("strong",[e._v("missing keys")]),e._v(" (entries fond in the project but not in the language files)")])]),e._v(" "),n("p",[e._v("It's possible to show the output in the console or to write it in a json file.")]),e._v(" "),n("p",[e._v("The missing keys can be also automatically added to the given language files.")])])}),[],!1,null,null,null);t.default=a.exports}}]); \ No newline at end of file diff --git a/assets/js/25.990df6a4.js b/assets/js/25.990df6a4.js new file mode 100644 index 000000000..87697c519 --- /dev/null +++ b/assets/js/25.990df6a4.js @@ -0,0 +1 @@ +(window.webpackJsonp=window.webpackJsonp||[]).push([[25],{472:function(t,e,s){"use strict";s.r(e);var a=s(44),n=Object(a.a)({},(function(){var t=this,e=t.$createElement,s=t._self._c||e;return s("ContentSlotsDistributor",{attrs:{"slot-key":t.$parent.slotKey}},[s("h1",{attrs:{id:"installation"}},[s("a",{staticClass:"header-anchor",attrs:{href:"#installation"}},[t._v("#")]),t._v(" Installation")]),t._v(" "),s("h2",{attrs:{id:"compatibility-note"}},[s("a",{staticClass:"header-anchor",attrs:{href:"#compatibility-note"}},[t._v("#")]),t._v(" Compatibility Note")]),t._v(" "),s("ul",[s("li",[t._v("Vue.js "),s("code",[t._v("2.0.0")]),t._v("+")])]),t._v(" "),s("h2",{attrs:{id:"direct-download-cdn"}},[s("a",{staticClass:"header-anchor",attrs:{href:"#direct-download-cdn"}},[t._v("#")]),t._v(" Direct Download / CDN")]),t._v(" "),s("p",[s("a",{attrs:{href:"https://unpkg.com/vue-i18n@8",target:"_blank",rel:"noopener noreferrer"}},[t._v("https://unpkg.com/vue-i18n@8"),s("OutboundLink")],1)]),t._v(" "),s("p",[s("a",{attrs:{href:"https://unpkg.com",target:"_blank",rel:"noopener noreferrer"}},[t._v("unpkg.com"),s("OutboundLink")],1),t._v(" provides NPM-based CDN links. The above link will always point to the latest release on NPM. You can also use a specific version/tag via URLs like "),s("a",{attrs:{href:"https://unpkg.com/vue-i18n@8.28.2/dist/vue-i18n.js",target:"_blank",rel:"noopener noreferrer"}},[t._v("https://unpkg.com/vue-i18n@8.28.2/dist/vue-i18n.js"),s("OutboundLink")],1)]),t._v(" "),s("p",[t._v("Include vue-i18n after Vue and it will install itself automatically:")]),t._v(" "),s("div",{staticClass:"language-html extra-class"},[s("pre",{pre:!0,attrs:{class:"language-html"}},[s("code",[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("script")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v("src")]),s("span",{pre:!0,attrs:{class:"token attr-value"}},[s("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),t._v("https://unpkg.com/vue/dist/vue.js"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),s("span",{pre:!0,attrs:{class:"token script"}}),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n"),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("<")]),t._v("script")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token attr-name"}},[t._v("src")]),s("span",{pre:!0,attrs:{class:"token attr-value"}},[s("span",{pre:!0,attrs:{class:"token punctuation attr-equals"}},[t._v("=")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')]),t._v("https://unpkg.com/vue-i18n@8"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v('"')])]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(">")])]),s("span",{pre:!0,attrs:{class:"token script"}}),s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token tag"}},[s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("")])]),t._v("\n")])])]),s("h2",{attrs:{id:"npm"}},[s("a",{staticClass:"header-anchor",attrs:{href:"#npm"}},[t._v("#")]),t._v(" NPM")]),t._v(" "),s("div",{staticClass:"language-sh extra-class"},[s("pre",{pre:!0,attrs:{class:"language-sh"}},[s("code",[s("span",{pre:!0,attrs:{class:"token function"}},[t._v("npm")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token function"}},[t._v("install")]),t._v(" vue-i18n@8\n")])])]),s("h2",{attrs:{id:"yarn"}},[s("a",{staticClass:"header-anchor",attrs:{href:"#yarn"}},[t._v("#")]),t._v(" Yarn")]),t._v(" "),s("div",{staticClass:"language-sh extra-class"},[s("pre",{pre:!0,attrs:{class:"language-sh"}},[s("code",[s("span",{pre:!0,attrs:{class:"token function"}},[t._v("yarn")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token function"}},[t._v("add")]),t._v(" vue-i18n@8\n")])])]),s("p",[t._v("When using with a module system, you must explicitly install the "),s("code",[t._v("vue-i18n")]),t._v("\nvia "),s("code",[t._v("Vue.use()")]),t._v(":")]),t._v(" "),s("div",{staticClass:"language-javascript extra-class"},[s("pre",{pre:!0,attrs:{class:"language-javascript"}},[s("code",[s("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("import")]),t._v(" Vue "),s("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("from")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token string"}},[t._v("'vue'")]),t._v("\n"),s("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("import")]),t._v(" VueI18n "),s("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("from")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token string"}},[t._v("'vue-i18n'")]),t._v("\n\nVue"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),s("span",{pre:!0,attrs:{class:"token function"}},[t._v("use")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v("VueI18n"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v("\n")])])]),s("p",[t._v("You don't need to do this when using global script tags "),s("code",[t._v(" + + diff --git a/guide/datetime.html b/guide/datetime.html new file mode 100644 index 000000000..cafc83f19 --- /dev/null +++ b/guide/datetime.html @@ -0,0 +1,159 @@ + + + + + + DateTime localization | Vue I18n + + + + + + + + + +

# DateTime localization

Support Version

🆕 7.0+

You can localize the datetime with your definition formats.

DateTime formats the below:

const dateTimeFormats = {
+  'en-US': {
+    short: {
+      year: 'numeric',
+      month: 'short',
+      day: 'numeric'
+    },
+    long: {
+      year: 'numeric',
+      month: 'long',
+      day: 'numeric',
+      weekday: 'long',
+      hour: 'numeric',
+      minute: 'numeric'
+    }
+  },
+  'ja-JP': {
+    short: {
+      year: 'numeric',
+      month: 'short',
+      day: 'numeric'
+    },
+    long: {
+      year: 'numeric',
+      month: 'long',
+      day: 'numeric',
+      weekday: 'long',
+      hour: 'numeric',
+      minute: 'numeric',
+      hour12: true
+    }
+  }
+}
+

As seen above, you can define named datetime format (e.g. short, long, etc), and you need to use the options with ECMA-402 Intl.DateTimeFormat (opens new window)

After that, when using the locale messages, you need to specify the dateTimeFormats option of the VueI18n constructor:

const i18n = new VueI18n({
+  dateTimeFormats
+})
+
+new Vue({
+  i18n
+}).$mount('#app')
+

Template the below:

<div id="app">
+  <p>{{ $d(new Date(), 'short') }}</p>
+  <p>{{ $d(new Date(), 'long', 'ja-JP') }}</p>
+</div>
+

Output the below:

<div id="app">
+  <p>Jan 18, 2021</p>
+  <p>2021年1月18日日曜日 午前5:47</p>
+</div>
+
+ + + diff --git a/guide/directive.html b/guide/directive.html new file mode 100644 index 000000000..6d0e08590 --- /dev/null +++ b/guide/directive.html @@ -0,0 +1,186 @@ + + + + + + Custom directive localization | Vue I18n + + + + + + + + + +

# Custom directive localization

Support Version

🆕 7.3+

You can translate not only with v-t custom directive, but also with the $t +method.

# String syntax

You can pass the keypath of locale messages with string syntax.

Javascript:

new Vue({
+  i18n: new VueI18n({
+    locale: 'en',
+    messages: {
+      en: { hello: 'hi there!' },
+      ja: { hello: 'こんにちは!' }
+    }
+  }),
+  data: { path: 'hello' }
+}).$mount('#string-syntax')
+

Templates:

<div id="string-syntax">
+  <!-- string literal -->
+  <p v-t="'hello'"></p>
+  <!-- keypath binding via data -->
+  <p v-t="path"></p>
+</div>
+

Outputs:

<div id="string-syntax">
+  <p>hi there!</p>
+  <p>hi there!</p>
+</div>
+

# Object syntax

You can use object syntax.

Javascript:

new Vue({
+  i18n: new VueI18n({
+    locale: 'en',
+    messages: {
+      en: { hello: 'hi {name}!' },
+      ja: { hello: 'こんにちは、{name}!' }
+    }
+  }),
+  computed: {
+    nickName () { return 'kazupon' }
+  },
+  data: { path: 'hello' }
+}).$mount('#object-syntax')
+

Templates:

<div id="object-syntax">
+  <!-- literal -->
+  <p v-t="{ path: 'hello', locale: 'ja', args: { name: 'kazupon' } }"></p>
+  <!-- data binding via data -->
+  <p v-t="{ path: path, args: { name: nickName } }"></p>
+</div>
+

Outputs:

<div id="object-syntax">
+  <p>こんにちは、kazupon!</p>
+  <p>hi kazupon!</p>
+</div>
+

# Use with transitions

Support Version

🆕 8.7+

When v-t directive is applied to an element inside <transition> component (opens new window), you may notice that the translated message disappears during the transition. This behavior is related to the nature of the <transition> component implementation – all directives in the disappearing element inside the <transition> component will be destroyed before the transition starts. This behavior may result in content flickering on short animations, but is most noticeable on long transitions.

To make sure directive content stays un-touched during a transition, just add the .preserve modifier to the v-t directive definition.

Javascript:

new Vue({
+  i18n: new VueI18n({
+    locale: 'en',
+    messages: {
+      en: { preserve: 'with preserve' },
+    }
+  }),
+  data: { toggle: true }
+}).$mount('#in-transitions')
+

Templates:

<div id="in-transitions">
+  <transition name="fade">
+    <span v-if="toggle" v-t.preserve="'preserve'"></span>
+  </transition>
+  <button @click="toggle = !toggle">Toggle</button>
+</div>
+

It is also possible to set global settings on the VueI18n instance itself, which will affect all v-t directives without modifier.

Javascript:

new Vue({
+  i18n: new VueI18n({
+    locale: 'en',
+    messages: {
+      en: { preserve: 'with preserve' },
+    },
+    preserveDirectiveContent: true
+  }),
+  data: { toggle: true }
+}).$mount('#in-transitions')
+

Templates:

<div id="in-transitions">
+  <transition name="fade">
+    <span v-if="toggle" v-t="'preserve'"></span>
+  </transition>
+  <button @click="toggle = !toggle">Toggle</button>
+</div>
+

About the above examples, see the example (opens new window)

# $t vs v-t

# $t

$t is an extended Vue instance method. It has the following pros and cons:

# Pros

You can flexibly use mustache syntax {{}} in templates and also computed props and methods in Vue instance.

# Cons

$t is executed every time when re-render occurs, so it does have translation costs.

# v-t

v-t is a custom directive. It has the following pros and cons:

# Pros

v-t has better performance than the $t method due to its cache with the custom directive, when translated once. Also, pre-translation is possible with the Vue compiler module which was provided by vue-i18n-extensions (opens new window).

Therefore it's possible to make more performance optimizations.

# Cons

v-t cannot be flexibly used like $t, it's rather complex. The translated content with v-t is inserted into the textContent of the element. Also, when you use server-side rendering, you need to set the custom directive (opens new window) to directives option of the createRenderer function.

+ + + diff --git a/guide/fallback.html b/guide/fallback.html new file mode 100644 index 000000000..660de9ee0 --- /dev/null +++ b/guide/fallback.html @@ -0,0 +1,160 @@ + + + + + + Fallback localization | Vue I18n + + + + + + + + + +

# Fallback localization

Summary: Use fallbackLocale: '<lang>' to choose which language to use when your preferred language lacks a translation.

# Implicit fallback using locales

If a locale is given containing a territory and an optional dialect, the implicit fallback is activated automatically.

For example de-DE-bavarian would fallback

  1. de-DE-bavarian
  2. de-DE
  3. de

To suppress the automatic fallback, add the postfix exclamation mark !, for example de-DE!

# Explicit fallback with one locale

Sometimes some items will not be translated into some languages. In this example, the item hello is available in English but not Japanese:

const messages = {
+  en: {
+    hello: 'Hello, world!'
+  },
+  ja: {
+    // Localization without translation to `hello`
+  }
+}
+

If you want to use (say) en items when an item is not available in your desired locale, set the fallbackLocale option in the VueI18n constructor:

const i18n = new VueI18n({
+  locale: 'ja',
+  fallbackLocale: 'en',
+  messages
+})
+

Template:

<p>{{ $t('hello') }}</p>
+

Output:

<p>Hello, world!</p>
+

By default, falling back to fallbackLocale generates two console warnings:

[vue-i18n] Value of key 'hello' is not a string!
+[vue-i18n] Fall back to translate the keypath 'hello' with 'en' locale.
+

To suppress these warnings (while keeping those which warn of the total absence of translation for the given key) set silentFallbackWarn: true when initializing the VueI18n instance.

# Explicit fallback with an array of locales

It is possible to set more than one fallback locale by using an array of locales. For example

fallbackLocale: [ 'fr', 'en' ],
+

# Explicit fallback with decision maps

If more complex decision maps for fallback locales are required, it is possible to define decision maps with according fallback locales. +Using the following decision map

fallbackLocale: {
+  /* 1 */ 'de-CH':   ['fr', 'it'],
+  /* 2 */ 'zh-Hant': ['zh-Hans'],
+  /* 3 */ 'es-CL':   ['es-AR'],
+  /* 4 */ 'es':      ['en-GB'],
+  /* 5 */ 'pt':      ['es-AR'],
+  /* 6 */ 'default': ['en', 'da']
+},
+

will result in the following fallback chains

locale fallback chains
'de-CH' de-CH > fr > it > en > da
'de' de > en > da
'zh-Hant' zh-Hant > zh-Hans > zh > en > da
'es-SP' es-SP > es > en-GB > en > da
'es-SP!' es-SP > en > da
'fr' fr > en > da
'pt-BR' pt-BR > pt > es-AR > es > en-GB > en > da
'es-CL' es-CL > es-AR > es > en-GB > en > da

# Fallback interpolation

Summary: Set formatFallbackMessages: true to do template interpolation on translation keys when your language lacks a translation for a key.

Since the keys to the translations are strings, you can use a user-readable message (for a particular language) as a key. +E.g.

const messages = {
+  ja: {
+    'Hello, world!': 'こんにちは、世界!'
+  }
+}
+

This is useful because you don't have to specify a translation for the string "Hello, world!" into English.

In fact, you can even include template parameters in a key. Together with formatFallbackMessages: true, this lets you skip writing templates for your "base" language; the keys are your templates.

const messages = {
+  ru: {
+    'Hello {name}': 'Здравствуйте {name}'
+  }
+}
+
+const i18n = new VueI18n({
+  locale: 'ru',
+  fallbackLocale: 'en',
+  formatFallbackMessages: true,
+  messages
+})
+

When the template is as below:

<p>{{ $t('Hello {name}', { name: 'John' }}) }}</p>
+<p>{{ $t('The weather today is {condition}!', { condition: 'sunny' }) }}</p>
+

The following will be output:

<p>Здравствуйте, John</p>
+<p>The weather today is sunny!</p>
+
+ + + diff --git a/guide/formatting.html b/guide/formatting.html new file mode 100644 index 000000000..d095067f6 --- /dev/null +++ b/guide/formatting.html @@ -0,0 +1,208 @@ + + + + + + Formatting | Vue I18n + + + + + + + + + +

# Formatting

# Named formatting

Locale messages:

const messages = {
+  en: {
+    message: {
+      hello: '{msg} world'
+    }
+  }
+}
+

Template:

<p>{{ $t('message.hello', { msg: 'hello' }) }}</p>
+

Output:

<p>hello world</p>
+

# List formatting

Locale messages:

const messages = {
+  en: {
+    message: {
+      hello: '{0} world'
+    }
+  }
+}
+

Template:

<p>{{ $t('message.hello', ['hello']) }}</p>
+

Output:

<p>hello world</p>
+

List formatting also accepts array-like objects:

<p>{{ $t('message.hello', {'0': 'hello'}) }}</p>
+

Output:

<p>hello world</p>
+

# HTML formatting

Notice

⚠️ Dynamically localizing arbitrary HTML on your website can be very dangerous because it can easily lead to XSS vulnerabilities. Only use HTML interpolation on trusted content and never on user-provided content.

We recommended using the component interpolation feature.

Notice

🆕 8.11+

You can control the use of HTML formatting. see the detail warnHtmlInMessage constructor option and property API.

In some cases you might want to render your translation as an HTML message and not a static string.

const messages = {
+  en: {
+    message: {
+      hello: 'hello <br> world'
+    }
+  }
+}
+

Template:

<p v-html="$t('message.hello')"></p>
+

Output (instead of the pre-formatted message )

<p>hello
+<!--<br> exists but is rendered as html and not a string-->
+world</p>
+

# Support ruby on rails i18n format

Locale messages:

const messages = {
+  en: {
+    message: {
+      hello: '%{msg} world'
+    }
+  }
+}
+

Template:

<p>{{ $t('message.hello', { msg: 'hello' }) }}</p>
+

Output:

<p>hello world</p>
+

# Custom formatting

Sometimes, you may need to translate using custom formatting (e.g. ICU message syntax (opens new window)).

You can do that with a custom formatter that implements the Formatter Interface (opens new window).

The following custom formatter with ES2015 class syntax:

// Custom Formatter implementation
+class CustomFormatter {
+     constructor (options) {
+       // ...
+     }
+
+     //
+     // interpolate
+     //
+     // @param {string} message
+     //   string of list or named format.
+     //   e.g.
+     //   - named formatting: 'Hi {name}'
+     //   - list formatting: 'Hi {0}'
+     //
+     // @param {Object | Array} values
+     //   values of `message` interpolation.
+     //   passed values with `$t`, `$tc` and `i18n` functional component.
+     //   e.g.
+     //   - $t('hello', { name: 'kazupon' }) -> passed values: Object `{ name: 'kazupon' }`
+     //   - $t('hello', ['kazupon']) -> passed values: Array `['kazupon']`
+     //   - `i18n` functional component (component interpolation)
+     //     <i18n path="hello">
+     //       <p>kazupon</p>
+     //       <p>how are you?</p>
+     //     </i18n>
+     //     -> passed values: Array (included VNode):
+     //        `[VNode{ tag: 'p', text: 'kazupon', ...}, VNode{ tag: 'p', text: 'how are you?', ...}]`
+     //
+     // @return {Array<any>}
+     //   interpolated values. you need to return the following:
+     //   - array of string, when is using `$t` or `$tc`.
+     //   - array included VNode object, when is using `i18n` functional component.
+     //
+     interpolate (message, values) {
+       // implement interpolation logic here
+       // ...
+
+       // return the interpolated array
+       return ['resolved message string']
+     }
+}
+
+// register with `formatter` option
+const i18n = new VueI18n({
+  locale: 'en-US',
+  formatter: new CustomFormatter(/* here the constructor options */),
+  messages: {
+    'en-US': {
+      // ...
+    },
+    // ...
+  }
+})
+
+// Run!
+new Vue({ i18n }).$mount('#app')
+

You can check the custom formatter official example (opens new window).

+ + + diff --git a/guide/hot-reload.html b/guide/hot-reload.html new file mode 100644 index 000000000..d907faf99 --- /dev/null +++ b/guide/hot-reload.html @@ -0,0 +1,193 @@ + + + + + + Hot reloading | Vue I18n + + + + + + + + + +

# Hot reloading

You can use Webpack's Hot Module Replacement (opens new window) (HMR) feature to watch for changes in localization files and hot reload changes into your application.

# Basic example

If you only use a static set of locales, you can hot reload those locales explicitly:

import Vue from "vue"
+import VueI18n from "vue-i18n"
+import en from './en'
+import ja from './ja'
+
+const messages = {
+  en,
+  ja
+}
+
+// VueI18n instance
+const i18n = new VueI18n({
+  locale: 'en',
+  messages
+})
+
+// Run app
+const app = new Vue({
+  i18n,
+  // ...
+}).$mount('#app')
+
+// Hot updates
+if (module.hot) {
+  module.hot.accept(['./en', './ja'], function () {
+    i18n.setLocaleMessage('en', require('./en').default)
+    i18n.setLocaleMessage('ja', require('./ja').default)
+    // Or the following hot updates via $i18n property
+    // app.$i18n.setLocaleMessage('en', require('./en').default)
+    // app.$i18n.setLocaleMessage('ja', require('./ja').default)
+  })
+}
+

# Advanced example

If you want to support a changing set of locales, you can hot reload those locales dynamically using require.context:

import Vue from "vue";
+import VueI18n from "vue-i18n";
+
+Vue.use(VueI18n);
+
+// Load all locales and remember context
+function loadMessages() {
+  const context = require.context("./locales", true, /[a-z0-9-_]+\.json$/i);
+
+  const messages = context
+    .keys()
+    .map((key) => ({ key, locale: key.match(/[a-z0-9-_]+/i)[0] }))
+    .reduce(
+      (messages, { key, locale }) => ({
+        ...messages,
+        [locale]: context(key),
+      }),
+      {}
+    );
+
+  return { context, messages };
+}
+
+const { context, messages } = loadMessages();
+
+// VueI18n instance
+const i18n = new VueI18n({
+  locale: "en",
+  messages,
+});
+
+// Run app
+const app = new Vue({
+  i18n,
+  // ...
+}).$mount('#app');
+
+// Hot updates
+if (module.hot) {
+  module.hot.accept(context.id, () => {
+    const { messages: newMessages } = loadMessages();
+
+    Object.keys(newMessages)
+      .filter((locale) => messages[locale] !== newMessages[locale])
+      .forEach((locale) => {
+        messages[locale] = newMessages[locale];
+        i18n.setLocaleMessage(locale, messages[locale]);
+      });
+  });
+}
+
+ + + diff --git a/guide/interpolation.html b/guide/interpolation.html new file mode 100644 index 000000000..7ba9c4be7 --- /dev/null +++ b/guide/interpolation.html @@ -0,0 +1,259 @@ + + + + + + Component interpolation | Vue I18n + + + + + + + + + +

# Component interpolation

# Basic Usage

Support Version

🆕 7.0+

Sometimes, we need to localize with a locale message that was included in a HTML tag or component. For example:

<p>I accept xxx <a href="/term">Terms of Service Agreement</a></p>
+

In the above message, if you use $t, you will probably try to compose the following locale messages:

const messages = {
+  en: {
+    term1: 'I Accept xxx\'s',
+    term2: 'Terms of Service Agreement'
+  }
+}
+

And your localized template may look like this:

<p>{{ $t('term1') }}<a href="/term">{{ $t('term2') }}</a></p>
+

Output:

<p>I accept xxx <a href="/term">Terms of Service Agreement</a></p>
+

This is very cumbersome, and if you configure the <a> tag in a locale message, there is a possibility of XSS vulnerabilities due to localizing with +v-html="$t('term')".

You can avoid it using the i18n functional component. For example:

<div id="app">
+  <!-- ... -->
+  <i18n path="term" tag="label" for="tos">
+    <a :href="url" target="_blank">{{ $t('tos') }}</a>
+  </i18n>
+  <!-- ... -->
+</div>
+
const messages = {
+  en: {
+    tos: 'Term of Service',
+    term: 'I accept xxx {0}.'
+  },
+  ja: {
+    tos: '利用規約',
+    term: '私は xxx の{0}に同意します。'
+  }
+}
+
+const i18n = new VueI18n({
+  locale: 'en',
+  messages
+})
+new Vue({
+  i18n,
+  data: {
+    url: '/term'
+  }
+}).$mount('#app')
+

the following output:

<div id="app">
+  <!-- ... -->
+  <label for="tos">
+    I accept xxx <a href="/term" target="_blank">Term of Service</a>.
+  </label>
+  <!-- ... -->
+</div>
+

About the above example, see the example (opens new window)

The children of i18n functional component are interpolated with locale message of path prop.

In the above example:

<a :href="url" target="_blank">{{ $t('tos') }}</a>

is interpolated with term locale message.

In the above example, the component interpolation follows the list formatting. The children of i18n functional component are interpolated by their order of appearance.

You can choose the root container's node type by specifying a tag prop. If omitted, it defaults to 'span'. You can also set it to the boolean value false to insert the child nodes directly without creating a root element.

# Slots syntax usage

Support Version

🆕 8.14+

It's more convenient to use the named slots syntax. For example:

<div id="app">
+  <!-- ... -->
+  <i18n path="info" tag="p">
+    <template v-slot:limit>
+      <span>{{ changeLimit }}</span>
+    </template>
+    <template v-slot:action>
+      <a :href="changeUrl">{{ $t('change') }}</a>
+    </template>
+  </i18n>
+  <!-- ... -->
+</div>
+
const messages = {
+  en: {
+    info: 'You can {action} until {limit} minutes from departure.',
+    change: 'change your flight',
+    refund: 'refund the ticket'
+  }
+}
+
+const i18n = new VueI18n({
+  locale: 'en',
+  messages
+})
+
+new Vue({
+  i18n,
+  data: {
+    changeUrl: '/change',
+    refundUrl: '/refund',
+    changeLimit: 15,
+    refundLimit: 30
+  }
+}).$mount('#app')
+

Outputs:

<div id="app">
+  <!-- ... -->
+  <p>
+    You can <a href="/change">change your flight</a> until <span>15</span> minutes from departure.
+  </p>
+  <!-- ... -->
+</div>
+

In Vue 2.6 and later, you can use the following slots syntax in templates:

<div id="app">
+  <!-- ... -->
+  <i18n path="info" tag="p">
+    <template #limit>
+      <span>{{ changeLimit }}</span>
+    </template>
+    <template #action>
+      <a :href="changeUrl">{{ $t('change') }}</a>
+    </template>
+  </i18n>
+  <!-- ... -->
+</div>
+

Limitation

⚠️ In i18n component, slots props are not supported.

# Places syntax usage

Important!!

In the next major version, the place and places props will be deprecated. Please switch to slots syntax.

Support Version

🆕 7.2+

Notice

⚠️ In i18n component, text content consisting of only white spaces will be omitted.

Named formatting is supported with the help of place attribute. For example:

<div id="app">
+  <!-- ... -->
+  <i18n path="info" tag="p">
+    <span place="limit">{{ changeLimit }}</span>
+    <a place="action" :href="changeUrl">{{ $t('change') }}</a>
+  </i18n>
+  <!-- ... -->
+</div>
+
const messages = {
+  en: {
+    info: 'You can {action} until {limit} minutes from departure.',
+    change: 'change your flight',
+    refund: 'refund the ticket'
+  }
+}
+
+const i18n = new VueI18n({
+  locale: 'en',
+  messages
+})
+new Vue({
+  i18n,
+  data: {
+    changeUrl: '/change',
+    refundUrl: '/refund',
+    changeLimit: 15,
+    refundLimit: 30
+  }
+}).$mount('#app')
+

Outputs:

<div id="app">
+  <!-- ... -->
+  <p>
+    You can <a href="/change">change your flight</a> until <span>15</span> minutes from departure.
+  </p>
+  <!-- ... -->
+</div>
+

Notice

⚠️ To use named formatting, all children of i18n component must have place attribute set. Otherwise it will fallback to list formatting.

If you still want to interpolate text content in named formatting, you could define places property on i18n component. For example:

<div id="app">
+  <!-- ... -->
+  <i18n path="info" tag="p" :places="{ limit: refundLimit }">
+    <a place="action" :href="refundUrl">{{ $t('refund') }}</a>
+  </i18n>
+  <!-- ... -->
+</div>
+

Outputs:

<div id="app">
+  <!-- ... -->
+  <p>
+    You can <a href="/refund">refund your ticket</a> until 30 minutes from departure.
+  </p>
+  <!-- ... -->
+</div>
+
+ + + diff --git a/guide/lazy-loading.html b/guide/lazy-loading.html new file mode 100644 index 000000000..f4e4edb93 --- /dev/null +++ b/guide/lazy-loading.html @@ -0,0 +1,168 @@ + + + + + + Lazy loading translations | Vue I18n + + + + + + + + + +

# Lazy loading translations

Loading all of your translation files at once is overkill and unnecessary.

Lazy loading or asynchronously loading the translation files is really easy when using Webpack.

Let´s assume we have a project directory similar to the one below:

our-cool-project
+-dist
+-src
+--routes
+--store
+--setup
+---i18n-setup.js
+--lang
+---en.js
+---it.js
+

The lang folder is where all of our translation files reside. The setup folder is where our arbitrary setup files like the i18n-setup, global component inits, plugin inits and other reside.

//i18n-setup.js
+import Vue from 'vue'
+import VueI18n from 'vue-i18n'
+import messages from '@/lang/en'
+import axios from 'axios'
+
+Vue.use(VueI18n)
+
+export const i18n = new VueI18n({
+  locale: 'en', // set locale
+  fallbackLocale: 'en',
+  messages // set locale messages
+})
+
+const loadedLanguages = ['en'] // our default language that is preloaded
+
+function setI18nLanguage (lang) {
+  i18n.locale = lang
+  axios.defaults.headers.common['Accept-Language'] = lang
+  document.querySelector('html').setAttribute('lang', lang)
+  return lang
+}
+
+export function loadLanguageAsync(lang) {
+  // If the same language
+  if (i18n.locale === lang) {
+    return Promise.resolve(setI18nLanguage(lang))
+  }
+
+  // If the language was already loaded
+  if (loadedLanguages.includes(lang)) {
+    return Promise.resolve(setI18nLanguage(lang))
+  }
+
+  // If the language hasn't been loaded yet
+  return import(/* webpackChunkName: "lang-[request]" */ `@/lang/${lang}.js`).then(
+    messages => {
+      i18n.setLocaleMessage(lang, messages.default)
+      loadedLanguages.push(lang)
+      return setI18nLanguage(lang)
+    }
+  )
+}
+

In short we are creating a new VueI18n instance as we normally would. Then we are creating a loadedLanguages array that will keep track of our loaded languages. Next is the setI18nLanguage function that will actually change the language in our vueI18n instance, axios and where ever else is needed.

The loadLanguageAsync function is what we will actually use to change the languages. Loading the new files is done via the import function, which is generously provided by Webpack and it allows us to load files dynamically, and because it uses promises we can easily wait for the loading to finish.

You can learn more about the import function in the Webpack documentation (opens new window).

Using the loadLanguageAsync function is straightforward. A common use case is inside a vue-router beforeEach hook.

router.beforeEach((to, from, next) => {
+  const lang = to.params.lang
+  loadLanguageAsync(lang).then(() => next())
+})
+

We could improve this by checking if the lang is actually supported by us or not, call reject so we can catch that in the beforeEach stopping the route transition.

+ + + diff --git a/guide/locale.html b/guide/locale.html new file mode 100644 index 000000000..fa3536487 --- /dev/null +++ b/guide/locale.html @@ -0,0 +1,143 @@ + + + + + + Locale changing | Vue I18n + + + + + + + + + +

# Locale changing

Normally, using the root Vue instance as the starting point, all child components are localized using the locale property of the VueI18n class as a reference.

Sometimes you might want to dynamically change the locale. In that case you can change the value of the locale property of the VueI18n instance.

const i18n = new VueI18n({
+  locale: 'ja', // set locale
+  ...
+})
+
+// create root Vue instance
+new Vue({
+  i18n,
+  ...
+}).$mount('#app')
+
+// change other locale
+i18n.locale = 'en'
+

Each component contains a VueI18n instance referenced as the $i18n property that can also be used to change the locale.

Example:

<template>
+  <div class="locale-changer">
+    <select v-model="$i18n.locale">
+      <option v-for="(lang, i) in langs" :key="`Lang${i}`" :value="lang">
+        {{ lang }}
+      </option>
+    </select>
+  </div>
+</template>
+
+<script>
+export default {
+  name: 'locale-changer',
+  data () {
+    return { langs: ['ja', 'en'] }
+  }
+}
+</script>
+

Notice

⚠️ Locale changing is ignored for components that use sync: false.

Component vs. root scope

⚠️ Changing $i18n.locale inside a component does not update the root locale. +If you rely on the root locale, for example when using root fallbacks, use $root.$i18n.locale instead of $i18n.locale.

+ + + diff --git a/guide/messages.html b/guide/messages.html new file mode 100644 index 000000000..9d821f507 --- /dev/null +++ b/guide/messages.html @@ -0,0 +1,240 @@ + + + + + + Locale messages syntax | Vue I18n + + + + + + + + + +

# Locale messages syntax

# Structure

Locale Messages syntax below:

// As Flowtype definition, Locale Messages syntax like BNF annotation
+type LocaleMessages = { [key: Locale]: LocaleMessageObject };
+type LocaleMessageObject = { [key: Path]: LocaleMessage };
+type LocaleMessageArray = LocaleMessage[];
+type MessageContext = {
+  list: (index: number) => mixed,
+  named: (key: string) => mixed,
+  linked: (key: string) => TranslateResult,
+  values: any, // NOTE: not compatible for vue-i18n@v9.x
+  path: string, // NOTE: not compatible for vue-i18n@v9.x
+  formatter: Formatter, // NOTE: not compatible for vue-i18n@v9.x
+  messages: LocaleMessages, // NOTE: not compatible for vue-i18n@v9.x
+  locale: Locale // NOTE: not compatible for vue-i18n@v9.x
+};
+type MessageFunction = (ctx: MessageContext) => string;
+type LocaleMessage = string | MessageFunction | LocaleMessageObject | LocaleMessageArray;
+type Locale = string;
+type Path = string;
+

Based on the above syntax, You can configure the following Locale Messages structure:

{
+  "en": {  // 'en' Locale
+    "key1": "this is message1", // basic
+    "nested": { // nested
+      "message1": "this is nested message1"
+    },
+    "errors": [ // array
+      "this is 0 error code message",
+      {  // object in array
+        "internal1": "this is internal 1 error message"
+      },
+      [  // array in array
+        "this is nested array error 1"
+      ]
+    ]
+  },
+  "ja": { // 'ja' Locale
+    // ...
+  }
+}
+

In the above Locale Messages structure, You can translate using below key paths.

<div id="app">
+  <!-- basic -->
+  <p>{{ $t('key1') }}</p>
+  <!-- nested -->
+  <p>{{ $t('nested.message1') }}</p>
+  <!-- array -->
+  <p>{{ $t('errors[0]') }}</p>
+  <!-- object in array -->
+  <p>{{ $t('errors[1].internal1') }}</p>
+  <!-- array in array -->
+  <p>{{ $t('errors[2][0]') }}</p>
+</div>
+

Output the following:

<div id="app">
+  <!-- basic -->
+  <p>this is message1</p>
+  <!-- nested -->
+  <p>this is nested message1</p>
+  <!-- array -->
+  <p>this is 0 error code message</p>
+  <!-- object in array -->
+  <p>this is internal 1 error message</p>
+  <!-- array in array -->
+  <p>this is nested array error 1</p>
+</div>
+

# Linked locale messages

If there's a translation key that will always have the same concrete text as another one you can just link to it. To link to another translation key, all you have to do is to prefix its contents with an @: sign followed by the full name of the translation key including the namespace you want to link to.

Locale messages the below:

const messages = {
+  en: {
+    message: {
+      the_world: 'the world',
+      dio: 'DIO:',
+      linked: '@:message.dio @:message.the_world !!!!'
+    }
+  }
+}
+

Template:

<p>{{ $t('message.linked') }}</p>
+

Output:

<p>DIO: the world !!!!</p>
+

# Formatting linked locale messages

If the language distinguish cases of character, you may need control the case of the linked locale messages. +Linked messages can be formatted with modifier @.modifier:key

The below modifiers are available currently.

  • upper: Uppercase all characters in the linked message.
  • lower: Lowercase all characters in the linked message.
  • capitalize: Capitalize the first character in the linked message.

Locale messages the below:

const messages = {
+  en: {
+    message: {
+      homeAddress: 'Home address',
+      missingHomeAddress: 'Please provide @.lower:message.homeAddress'
+    }
+  }
+}
+
<label>{{ $t('message.homeAddress') }}</label>
+
+<p class="error">{{ $t('message.missingHomeAddress') }}</p>
+

Output the below:

<label>Home address</label>
+
+<p class="error">Please provide home address</p>
+

You can add modifiers or overwrite the existing ones passing the modifiers options to the VueI18n constructor.

const i18n = new VueI18n({
+  locale: 'en',
+  modifiers: {
+    // Adding a new modifier
+    snakeCase: (str) => str.split(' ').join('-')
+  },
+  messages: {
+    // ...
+  },
+})
+

# Grouping by brackets

A translation key of linked locale message can also have the form of @:(message.foo.bar.baz) in which the link to another translation key is within brackets ().

This can be useful if the link @:message.something is followed by period ., which otherwise would be part of the link and may not need to be.

Locale messages:

const messages = {
+  en: {
+    message: {
+      dio: 'DIO',
+      linked: 'There\'s a reason, you lost, @:(message.dio).'
+    }
+  }
+}
+

Template:

<p>{{ $t('message.linked') }}</p>
+

Output:

<p>There's a reason, you lost, DIO.</p>
+

# Message Function

vue-i18n recommends using the string base on list or named format as locale messages when translating messages.

There are situations however, where you really need the full programmatic power of JavaScript, due to the complex language syntax. So instead of string-based messages, you can use the message function.

The following is a message function that returns a simple greeting:

const messages = {
+  en: {
+    greeting: (ctx) => 'hello!'
+  }
+}
+

The use of the message function is very easy! You just specify the key of the message function with $t or t:

<p>{{ $t('greeting') }}</p>
+

Output is the below:

<p>hello!</p>
+

The message function outputs the message of the return value of the message function.

# Named formatting

vue-i18n supports named formatting as a string-based message format. vue-i18n interpolate the parameter values with $t or t, and it can be output it.

You can do the same thing with the message function by using message context:

here is the example of greeting:

const messages = {
+  en: {
+    greeting: (ctx) => `hello, ${ctx.named('name')}!`
+  }
+}
+

Template:

<p>{{ $t('greeting', { name: 'DIO' }) }}</p>
+

Output is the below:

<p>hello, DIO!</p>
+

The message context has a named function. You need to specify the key that resolves the value specified with the named of $t or t.

# List formatting

The use of the list format is similar to the named format described above.

vue-i18n supports list formatting as a string-based message format. vue-i18n interpolate the parameter values with $t or t, and it can be output it.

You can do the same thing with the message function by using message context:

here is the example of greeting:

const messages = {
+  en: {
+    greeting: (ctx) => `hello, ${ctx.list(0)}!`
+  }
+}
+

Template:

<p>{{ $t('greeting', ['DIO']) }}</p>
+

Output is the below:

<p>hello, DIO!</p>
+

The message context has a list function. You need to specify the index that resolves the value specified with the list of $t or t.

# Limitation

In the message function, the following functions, which are provided on a string basis, are not available via a message context:

  • Pluralization

And also, the following props of message context is not compatible for vue-i18 v9.x or later:

  • path
  • locale
  • messages
  • formatter

If you are using these message context props means that it will be difficult to migrate to vue-i18n v9.x or later.

+ + + diff --git a/guide/number.html b/guide/number.html new file mode 100644 index 000000000..caa2ecf34 --- /dev/null +++ b/guide/number.html @@ -0,0 +1,178 @@ + + + + + + Number localization | Vue I18n + + + + + + + + + +

# Number localization

Support Version

🆕 7.0+

You can localize the number with your definition formats.

Number formats the below:

const numberFormats = {
+  'en-US': {
+    currency: {
+      style: 'currency',
+      currency: 'USD'
+    }
+  },
+  'ja-JP': {
+    currency: {
+      style: 'currency',
+      currency: 'JPY',
+      currencyDisplay: 'symbol'
+    }
+  }
+}
+

As the above, you can define named number formats (e.g. currency, etc), and you need to use the options with ECMA-402 Intl.NumberFormat (opens new window)

After that, when using the locale messages, you need to specify the numberFormats option of the VueI18n constructor:

const i18n = new VueI18n({
+  numberFormats
+})
+
+new Vue({
+  i18n
+}).$mount('#app')
+

Template the below:

<div id="app">
+  <p>{{ $n(100, 'currency') }}</p>
+  <p>{{ $n(100, 'currency', 'ja-JP') }}</p>
+</div>
+

Output the below:

<div id="app">
+  <p>$100.00</p>
+  <p>¥100</p>
+</div>
+

# Custom formatting

Support Version

🆕 8.10+

$n method returns resulting string with fully formatted number, which can only be used as a whole. In situations when you need to style some part of the formatted number (like fraction digits), $n is not enough. In such cases <i18n-n> functional component will be of help.

With a minimum set of properties, <i18n-n> generates the same output as $n, wrapped into configured DOM element.

The following template:

<div id="app">
+  <i18n-n :value="100"></i18n-n>
+  <i18n-n :value="100" format="currency"></i18n-n>
+  <i18n-n :value="100" format="currency" locale="ja-JP"></i18n-n>
+</div>
+

will produce the below output:

<div id="app">
+  <span>100</span>
+  <span>$100.00</span>
+  <span>¥100</span>
+</div>
+

But the real power of this component comes into play when it is used with scoped slots (opens new window).

Let's say there is a requirement to render the integer part of the number with a bolder font. This can be achieved by specifying integer scoped slot element:

<i18n-n :value="100" format="currency">
+  <template v-slot:integer="slotProps">
+    <span style="font-weight: bold">{{ slotProps.integer }}</span>
+  </template>
+</i18n-n>
+

Template above will result in the following HTML:

<span>$<span style="font-weight: bold">100</span>.00</span>
+

It is possible to specify multiple scoped slots at the same time:

<i18n-n :value="1234" :format="{ key: 'currency', currency: 'EUR' }">
+  <template v-slot:currency="slotProps">
+    <span style="color: green">{{ slotProps.currency }}</span>
+  </template>
+  <template v-slot:integer="slotProps">
+    <span style="font-weight: bold">{{ slotProps.integer }}</span>
+  </template>
+  <template v-slot:group="slotProps">
+    <span style="font-weight: bold">{{ slotProps.group }}</span>
+  </template>
+  <template v-slot:fraction="slotProps">
+    <span style="font-size: small">{{ slotProps.fraction }}</span>
+  </template>
+</i18n-n>
+

(this resulting HTML was formatted for better readability)

<span>
+  <span style="color: green"></span>
+  <span style="font-weight: bold">1</span>
+  <span style="font-weight: bold">,</span>
+  <span style="font-weight: bold">234</span>
+  <span style="font-size: small">00</span>
+</span>
+

You can choose the root container's node type by specifying a tag prop. If omitted, it defaults to 'span'. You can also set it to the boolean value false to insert the child nodes directly without creating a root element.

Full list of the supported scoped slots as well as other <i18n-n> properties can be found on API page.

+ + + diff --git a/guide/pluralization.html b/guide/pluralization.html new file mode 100644 index 000000000..ef91ab7b0 --- /dev/null +++ b/guide/pluralization.html @@ -0,0 +1,209 @@ + + + + + + Pluralization | Vue I18n + + + + + + + + + +

# Pluralization

You can translate with pluralization. You must define the locale that have a pipe | separator, and define plurals in pipe separator.

Your template will need to use $tc() instead of $t().

Locale messages below:

const messages = {
+  en: {
+    car: 'car | cars',
+    apple: 'no apples | one apple | {count} apples'
+  }
+}
+

Template below:

<p>{{ $tc('car', 1) }}</p>
+<p>{{ $tc('car', 2) }}</p>
+
+<p>{{ $tc('apple', 0) }}</p>
+<p>{{ $tc('apple', 1) }}</p>
+<p>{{ $tc('apple', 10, { count: 10 }) }}</p>
+

Output below:

<p>car</p>
+<p>cars</p>
+
+<p>no apples</p>
+<p>one apple</p>
+<p>10 apples</p>
+

# Accessing the number via the pre-defined argument

You don't need to explicitly give the number for pluralization. +The number can be accessed within locale messages via pre-defined named arguments {count} and/or {n}. +You can overwrite those pre-defined named arguments if necessary.

Locale messages the below:

const messages = {
+  en: {
+    apple: 'no apples | one apple | {count} apples',
+    banana: 'no bananas | {n} banana | {n} bananas'
+  }
+}
+

Template below:

<p>{{ $tc('apple', 10, { count: 10 }) }}</p>
+<p>{{ $tc('apple', 10) }}</p>
+
+<p>{{ $tc('banana', 1, { n: 1 }) }}</p>
+<p>{{ $tc('banana', 1) }}</p>
+<p>{{ $tc('banana', 100, { n: 'too many' }) }}</p>
+

Output below:

<p>10 apples</p>
+<p>10 apples</p>
+
+<p>1 banana</p>
+<p>1 banana</p>
+<p>too many bananas</p>
+

# Custom pluralization

This feature is available since version 8.0

Such pluralization, however, does not apply to all languages (Slavic languages, for example, have different pluralization rules).

In order to implement these rules you can pass an optional pluralizationRules object into VueI18n constructor options.

Very simplified example using rules for Slavic languages (Russian, Ukrainian, etc.):

new VueI18n({
+  // Key - language to use the rule for, `'ru'`, in this case
+  // Value - function to choose right plural form
+  pluralizationRules: {
+    /**
+     * @param choice {number} a choice index given by the input to $tc: `$tc('path.to.rule', choiceIndex)`
+     * @param choicesLength {number} an overall amount of available choices
+     * @returns a final choice index to select plural word by
+     */
+    'ru': function(choice, choicesLength) {
+      // this === VueI18n instance, so the locale property also exists here
+
+      if (choice === 0) {
+        return 0;
+      }
+
+      const teen = choice > 10 && choice < 20;
+      const endsWithOne = choice % 10 === 1;
+
+      if (choicesLength < 4) {
+        return (!teen && endsWithOne) ? 1 : 2;
+      }
+      if (!teen && endsWithOne) {
+        return 1;
+      }
+      if (!teen && choice % 10 >= 2 && choice % 10 <= 4) {
+        return 2;
+      }
+
+      return (choicesLength < 4) ? 2 : 3;
+    }
+  }
+})
+

This would effectively give this:

const messages = {
+  ru: {
+    car: '0 машин | {n} машина | {n} машины | {n} машин',
+    banana: 'нет бананов | {n} банан | {n} банана | {n} бананов'
+  }
+}
+

Where the format is 0 things | things count ends with 1 | things count ends with 2-4 | things count ends with 5-9, 0 and teens (10-19). +P.S. Slavic pluralization is difficult, you can read more about it here (opens new window).

Your template still needs to use $tc(), not $t():

<p>{{ $tc('car', 1) }}</p>
+<p>{{ $tc('car', 2) }}</p>
+<p>{{ $tc('car', 4) }}</p>
+<p>{{ $tc('car', 12) }}</p>
+<p>{{ $tc('car', 21) }}</p>
+
+<p>{{ $tc('banana', 0) }}</p>
+<p>{{ $tc('banana', 4) }}</p>
+<p>{{ $tc('banana', 11) }}</p>
+<p>{{ $tc('banana', 31) }}</p>
+

Which results in:

<p>1 машина</p>
+<p>2 машины</p>
+<p>4 машины</p>
+<p>12 машин</p>
+<p>21 машина</p>
+
+<p>нет бананов</p>
+<p>4 банана</p>
+<p>11 бананов</p>
+<p>31 банан</p>
+

# Default pluralization

If your current locale is not found in a pluralization map, the default rule of the english language will be used.

+ + + diff --git a/guide/sfc.html b/guide/sfc.html new file mode 100644 index 000000000..0b035dc53 --- /dev/null +++ b/guide/sfc.html @@ -0,0 +1,398 @@ + + + + + + Single file components | Vue I18n + + + + + + + + + +

# Single file components

# Basic Usage

If you are building Vue component or Vue application using single file components, you can manage the locale messages i18n custom block.

The following in single file components example (opens new window):

<i18n>
+{
+  "en": {
+    "hello": "hello world!"
+  },
+  "ja": {
+    "hello": "こんにちは、世界!"
+  }
+}
+</i18n>
+
+<template>
+  <div id="app">
+    <label for="locale">locale</label>
+    <select v-model="locale">
+      <option>en</option>
+      <option>ja</option>
+    </select>
+    <p>message: {{ $t('hello') }}</p>
+  </div>
+</template>
+
+<script>
+export default {
+  name: 'app',
+  data () {
+    this.$i18n.locale = 'en';
+    return { locale: 'en' }
+  },
+  watch: {
+    locale (val) {
+      this.$i18n.locale = val
+    }
+  }
+}
+</script>
+

# Installing vue-i18n-loader

You need to install vue-loader and vue-i18n-loader to use <i18n> custom blocks. While vue-loader (opens new window) most likely is already used in your project if you are working with single file components, you must install vue-i18n-loader (opens new window) additionally:

npm i --save-dev @intlify/vue-i18n-loader
+

# Webpack

For Webpack the configuration below is required:

for vue-loader v15 or later:

module.exports = {
+  // ...
+  module: {
+    rules: [
+      {
+        test: /\.vue$/,
+        loader: 'vue-loader',
+      },
+      {
+        resourceQuery: /blockType=i18n/,
+        type: 'javascript/auto',
+        loader: '@intlify/vue-i18n-loader'
+      }
+      // ...
+    ]
+  },
+  // ...
+}
+

for vue-loader v14:

module.exports = {
+  // ...
+  module: {
+    rules: [
+      {
+        test: /\.vue$/,
+        loader: 'vue-loader',
+        options: {
+          loaders: {
+            // you need to specify `i18n` loaders key with `vue-i18n-loader` (https://github.com/intlify/vue-i18n-loader)
+            i18n: '@intlify/vue-i18n-loader'
+          }
+        }
+      },
+      // ...
+    ]
+  },
+  // ...
+}
+

# Vue CLI 3.0

Vue CLI 3.0 (opens new window) hides the webpack configuration, so, if we want to add support to the <i18n> tag inside a single file component we need to modify the existing configuration.

In order to do that we have to create a vue.config.js at the root of our project. Once we have done that, we have to include the following:

for vue-loader v15 or later:

module.exports = {
+  chainWebpack: config => {
+    config.module
+      .rule("i18n")
+      .resourceQuery(/blockType=i18n/)
+      .type('javascript/auto')
+      .use("i18n")
+        .loader("@intlify/vue-i18n-loader")
+        .end();
+  }
+}
+

for vue-loader v14:

const merge = require('deepmerge')
+
+module.exports = {
+  chainWebpack: config => {
+    config.module
+      .rule('vue')
+      .use('vue-loader')
+      .tap(options =>
+        merge(options, {
+          loaders: {
+            i18n: '@intlify/vue-i18n-loader'
+          }
+        })
+      )
+  }
+}
+

Don 't forget to install deepmerge (opens new window)! (npm i deepmerge -D or yarn add deepmerge -D)

If you want to read more about modifying the existing configuration click here (opens new window).

# Laravel-Mix

for Laravel-mix 4 with vue-loader v15 or later:

// Extend Mix with the "i18n" method, that loads the vue-i18n-loader
+mix.extend( 'i18n', new class {
+        webpackRules() {
+            return [
+                {
+                    resourceQuery: /blockType=i18n/,
+                    type:          'javascript/auto',
+                    loader:        '@intlify/vue-i18n-loader',
+                },
+            ];
+        }
+    }(),
+);
+
+// Make sure to call the .i18n() (to load the loader) before .js(..., ...)
+mix.i18n()
+   .js( 'resources/js/App.js', 'public/js/app.js' )
+   ...
+

for Laravel-mix 2 with vue-loader v14:

As of V2.1 (opens new window) of Laravel-mix, you can add custom rules via mix.extend(). Laravel mix already has its own rules for handling .vue files. To add the vue-i18n-loader, add the following to webpack.mix.js

// The below code will inject i18n Kazupon/vue-18-loader as a loader for .vue files.
+mix.extend( 'i18n', function( webpackConfig, ...args ) {
+    webpackConfig.module.rules.forEach( ( module ) => {
+        // Search for the "vue-loader" component, which handles .vue files.
+        if( module.loader !== 'vue-loader' ) {
+            return;
+        }
+
+        // Within this module, add the vue-i18n-loader for the i18n tag.
+        module.options.loaders.i18n = '@intlify/vue-i18n-loader';
+    } );
+} );
+
+// Make sure to call .i18n() before .js(..., ...)
+mix.i18n()
+   .js( 'resources/assets/js/App.js', 'public/js/app.js' )
+   ...
+

# YAML loading

i18n custom blocks need to specify JSON format, also you can use YAML format by using pre-loader feature of vue-loader.

the i18n custom blocks below of YAML format:

<i18n>
+en:
+  hello: "hello world!"
+ja:
+  hello: "こんにちは、世界!"
+</i18n>
+

Webpack conf the below:

for vue-loader v15 or later:

// Vue CLI 3.0
+module.exports = {
+  chainWebpack: config => {
+    config.module
+      .rule("i18n")
+      .resourceQuery(/blockType=i18n/)
+      .type('javascript/auto')
+      .use("i18n")
+        .loader("@intlify/vue-i18n-loader")
+        .end()
+      .use('yaml')
+        .loader('yaml-loader')
+        .end()
+  }
+}
+

for vue-loader v14:

module.exports = {
+  // ...
+  module: {
+    rules: [
+      {
+        test: /\.vue$/,
+        loader: 'vue-loader',
+        options: {
+          preLoaders: {
+            i18n: 'yaml-loader'
+          },
+          loaders: {
+            i18n: '@intlify/vue-i18n-loader'
+          }
+        }
+      },
+      // ...
+    ]
+  },
+  // ...
+}
+

# Multiple custom blocks

You can use locale messages with multiple i18n custom blocks.

<i18n src="./common/locales.json"></i18n>
+<i18n>
+  {
+    "en": {
+      "hello": "hello world!"
+    },
+    "ja": {
+      "hello": "こんにちは、世界!"
+    }
+  }
+</i18n>
+

In the above, first custom block load the common locale message with src attribute, second custom block load the locale message that is defined only at single file component. These locale messages will be merged as locale message of component.

In this way, multiple custom blocks useful when want to be used as module.

# Scoped style

When using vue-i18n with scoped style, it's important to remember to use a deep selector (opens new window) for styling an element inside the translation string. For example:

Translation contains only text (Work without deep selector)

<i18n>
+{
+  "en": {
+    "hello": "hello world!"
+  },
+  "ja": {
+    "hello": "こんにちは、世界"
+  }
+}
+</i18n>
+
+<template>
+  <div class="parent">
+    <p>message: {{ $t('hello') }}</p>
+  </div>
+</template>
+
+<!-- Will work -->
+<style scoped>
+  .parent p {
+    color: #42b883;
+  }
+</style>
+

Translation with HTML element (Must use deep selector)

<i18n>
+{
+  "en": {
+    "hello": "hello<span>world!</span>"
+  },
+  "ja": {
+    "hello": "こんにちは、<span>世界!</span>"
+  }
+}
+</i18n>
+
+<template>
+  <div class="parent">
+    <p v-html="$t('hello')"></p>
+  </div>
+</template>
+
+<!-- Won't work -->
+<style scoped>
+  .parent p {
+    color: #42b883;
+  }
+
+  .parent p span {
+    color: red;
+  }
+</style>
+
+<!-- Will work >>> -->
+<style scoped>
+  .parent p {
+    color: #42b883;
+  }
+
+  .parent p >>> span {
+    color: red;
+  }
+</style>
+
+<!-- Will work /deep/ -->
+<style scoped>
+  .parent p {
+    color: #42b883;
+  }
+
+  .parent p /deep/ span {
+    color: red;
+  }
+</style>
+
+<!-- Will work ::v-deep -->
+<style scoped>
+  .parent p {
+    color: #42b883;
+  }
+
+  ::v-deep .parent p span {
+    color: red;
+  }
+</style>
+

# Custom blocks in functional component

If the single file components have the template using a functional component, and you had been defined i18n custom blocks, note you cannot localize using locale messages.

For example, the following code cannot localize with the locale message of i18n custom block.

<i18n>
+{
+  "en": {
+    "hello": "hello world"
+  },
+  "ja": {
+    "hello": "こんにちは、世界"
+  }
+}
+</i18n>
+
+<template functional>
+  <!-- 'hello' of locale messages of parent instance -->
+  <p>{{ parent.$t('hello') }}</p>
+</template>
+
+ + + diff --git a/guide/tooling.html b/guide/tooling.html new file mode 100644 index 000000000..f8c975613 --- /dev/null +++ b/guide/tooling.html @@ -0,0 +1,107 @@ + + + + + + Tooling | Vue I18n + + + + + + + + + +

# Tooling

To support the i18n of Vue applications, some tools are officially provided.

There are also tools from third vendors integrating Vue I18n.

# Official tooling

# Vue CLI Plugin

vue-cli-plugin-i18n (opens new window) is officially provided as the Vue CLI Plugin.

With this plugin, you can setup the i18n environment for the Vue application, and support the i18n development environment.

# Nuxt Module

nuxt-i18n (opens new window) is corresponding Nuxt.js module.

# Webpack loader

vue-i18n-loader (opens new window) is an officially provided webpack loader.

With this loader, you can use the i18n custom block in the Single file components.

In about i18n custom block, see the Single file components section

# ESLint Plugin

eslint-plugin-vue-i18n (opens new window) is ESLint plugin for Vue I18n.

It easily integrates some localization lint features to your Vue.js Application.

# Extensions

vue-i18n-extensions (opens new window) provides some extensions for Vue I18n.

You can use this extension to enable SSR and improve i18n performance.

# 3rd party tooling

# BabelEdit

BabelEdit (opens new window) is translation editor for web apps.

BabelEdit can translate json files, and it can also translate i18n custom block of Single-file components.

Read more about BabelEdit in tutorial page (opens new window).

# i18n Ally

i18n Ally (opens new window) is i18n extension for VSCode.

i18n Ally give awesome DX for your i18n development.

Read more about i18n Ally in README (opens new window).

# i18nPlugin (intellij platform)

i18nPlugin (opens new window) Intellij idea i18next support plugin ( Jetbrains plugin page (opens new window)).

Plugin for i18n typescript/javascript/PHP. Supports vue-i18n. To enable vue-i18n support go to settings -> Tools -> i18n Plugin configuration and check "Vue-i18n". You need set vue locales directory (locales by default).

# vue-i18n-extract

vue-i18n-extract (opens new window) performs static analysis on a Vue.js project based on vue-i18n and reports the following information:

  • list of all the unused vue-i18n keys (entries found in the language files but not used in the project)
  • list of all the missing keys (entries fond in the project but not in the language files)

It's possible to show the output in the console or to write it in a json file.

The missing keys can be also automatically added to the given language files.

+ + + diff --git a/index.html b/index.html new file mode 100644 index 000000000..a15e0e7fa --- /dev/null +++ b/index.html @@ -0,0 +1,113 @@ + + + + + + Vue I18n + + + + + + + + + +
hero

+ Vue I18n +

+ Vue I18n is internationalization plugin for Vue.js +

+ Get Started → +

Easy

You can introduce internationalization into your app with simple API

Powerful

In addition to simple translation, support localization such as pluralization, number, datetime ... etc

Component-oriented

You can manage locale messages on single file component

🏅 Platinum Sponsors

zenarchitects

✨ Special Sponsors

PLAID

🥇 Gold Sponsors

NuxtLabs Localazy Crowdin

🥈 Silver Sponsors

🥉 Bronze Sponsors

vuemastery vuemastery
+ + + diff --git a/installation.html b/installation.html new file mode 100644 index 000000000..15f52889a --- /dev/null +++ b/installation.html @@ -0,0 +1,126 @@ + + + + + + Installation | Vue I18n + + + + + + + + + +

# Installation

# Compatibility Note

  • Vue.js 2.0.0+

# Direct Download / CDN

https://unpkg.com/vue-i18n@8 (opens new window)

unpkg.com (opens new window) provides NPM-based CDN links. The above link will always point to the latest release on NPM. You can also use a specific version/tag via URLs like https://unpkg.com/vue-i18n@8.28.2/dist/vue-i18n.js (opens new window)

Include vue-i18n after Vue and it will install itself automatically:

<script src="https://unpkg.com/vue/dist/vue.js"></script>
+<script src="https://unpkg.com/vue-i18n@8"></script>
+

# NPM

npm install vue-i18n@8
+

# Yarn

yarn add vue-i18n@8
+

When using with a module system, you must explicitly install the vue-i18n +via Vue.use():

import Vue from 'vue'
+import VueI18n from 'vue-i18n'
+
+Vue.use(VueI18n)
+

You don't need to do this when using global script tags <script>.

# Vue Cli 3.x

vue add i18n
+

You need Vue cli 3.x as pre-requisite, you can install it on your shell with the next command:

npm install @vue/cli -g
+

# Dev Build

You will have to clone directly from GitHub and build vue-i18n yourself if you want to use the latest dev build.

git clone https://github.com/kazupon/vue-i18n.git node_modules/vue-i18n
+cd node_modules/vue-i18n
+npm install # or `yarn`
+npm run build  # or `yarn run build`
+

# Explanation of Different Builds

In the dist/ directory of the NPM package (opens new window) you will find many different builds of VueI18n. Here’s an overview of the difference between them:

  • UMD: vue-i18n.js
  • CommonJS: vue-i18n.common.js
  • ES Module for bundlers: vue-i18n.esm.js
  • ES Module for browsers: vue-i18n.esm.browser.js

# Terms

+ + + diff --git a/introduction.html b/introduction.html new file mode 100644 index 000000000..8cf30d0d4 --- /dev/null +++ b/introduction.html @@ -0,0 +1,107 @@ + + + + + + Introduction | Vue I18n + + + + + + + + + +

# Introduction

Notice

You are reading the documentation of Vue I18n v8.x for Vue 2. If you are working with Vue 3, use the Vue I18n v9 documentation (opens new window) instead.

Vue I18n is internationalization plugin of Vue.js. It easily integrates some localization features to your Vue.js Application.

Go to Get Started

# Sponsors

# 🏅 Platinum

zenarchitects

# ✨ Special

PLAID

# 🥇 Gold

NuxtLabs

Localazy

Crowdin

# 🥈 Silver

# 🥉 Bronze

vuemastery

vuemastery

# Become a Sponsor

Is your company using vue-i18n, vue-cli-plugin-i18n and other tools to build awesome apps? Join the GitHub and become a sponsor to add your logo on this documentation! Supporting me on Sponsor allows me to work less for a job and to work more on Free Open Source Software such as vue-i18n and Intlify (opens new window) projects! Thank you!

+ + + diff --git a/patrons/Froggly.svg b/patrons/Froggly.svg new file mode 100644 index 000000000..6ff4a6289 --- /dev/null +++ b/patrons/Froggly.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/patrons/RapidAPI.png b/patrons/RapidAPI.png new file mode 100644 index 000000000..ada74016b Binary files /dev/null and b/patrons/RapidAPI.png differ diff --git a/patrons/RapidAPI.svg b/patrons/RapidAPI.svg new file mode 100644 index 000000000..4ddd1beeb --- /dev/null +++ b/patrons/RapidAPI.svg @@ -0,0 +1,28 @@ + + + + RapidAPI Logo Blue + Created with Sketch. + + + + + \ No newline at end of file diff --git a/patrons/babeledit.png b/patrons/babeledit.png new file mode 100644 index 000000000..13e250d8a Binary files /dev/null and b/patrons/babeledit.png differ diff --git a/patrons/babeledit.svg b/patrons/babeledit.svg new file mode 100644 index 000000000..14a37c1d9 --- /dev/null +++ b/patrons/babeledit.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/patrons/crowdin.png b/patrons/crowdin.png new file mode 100644 index 000000000..1291e8a17 Binary files /dev/null and b/patrons/crowdin.png differ diff --git a/patrons/crowdin.svg b/patrons/crowdin.svg new file mode 100644 index 000000000..846a4b090 --- /dev/null +++ b/patrons/crowdin.svg @@ -0,0 +1,16 @@ + + + + + + + + + + + + + + + + diff --git a/patrons/crowdin_back.svg b/patrons/crowdin_back.svg new file mode 100644 index 000000000..4fe34be42 --- /dev/null +++ b/patrons/crowdin_back.svg @@ -0,0 +1,11 @@ + + + + + + + + + + + diff --git a/patrons/cypress.svg b/patrons/cypress.svg new file mode 100644 index 000000000..7e33a941d --- /dev/null +++ b/patrons/cypress.svg @@ -0,0 +1,22 @@ + + + + + + + + + + + + + + + + + + + + + + diff --git a/patrons/decibel.png b/patrons/decibel.png new file mode 100644 index 000000000..980245c20 Binary files /dev/null and b/patrons/decibel.png differ diff --git a/patrons/localazy.svg b/patrons/localazy.svg new file mode 100644 index 000000000..c86ec7934 --- /dev/null +++ b/patrons/localazy.svg @@ -0,0 +1,12 @@ + + + + + + + + + + + + diff --git a/patrons/locize.png b/patrons/locize.png new file mode 100644 index 000000000..f7008dd7f Binary files /dev/null and b/patrons/locize.png differ diff --git a/patrons/nuxt.png b/patrons/nuxt.png new file mode 100644 index 000000000..a5032eede Binary files /dev/null and b/patrons/nuxt.png differ diff --git a/patrons/nuxtlabs.svg b/patrons/nuxtlabs.svg new file mode 100644 index 000000000..dc694d9b9 --- /dev/null +++ b/patrons/nuxtlabs.svg @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/patrons/plaid.svg b/patrons/plaid.svg new file mode 100644 index 000000000..78354f007 --- /dev/null +++ b/patrons/plaid.svg @@ -0,0 +1 @@ +plaid_yoko \ No newline at end of file diff --git a/patrons/sendcloud.png b/patrons/sendcloud.png new file mode 100644 index 000000000..1b536605c Binary files /dev/null and b/patrons/sendcloud.png differ diff --git a/patrons/sendcloud.svg b/patrons/sendcloud.svg new file mode 100644 index 000000000..fdde64b0d --- /dev/null +++ b/patrons/sendcloud.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/patrons/storyblok.svg b/patrons/storyblok.svg new file mode 100644 index 000000000..b80e8fe33 --- /dev/null +++ b/patrons/storyblok.svg @@ -0,0 +1,18 @@ + + + + colored-full + Created with Sketch. + + + + + \ No newline at end of file diff --git a/patrons/vuemastery.png b/patrons/vuemastery.png new file mode 100644 index 000000000..e163a9562 Binary files /dev/null and b/patrons/vuemastery.png differ diff --git a/patrons/vuemastery.svg b/patrons/vuemastery.svg new file mode 100644 index 000000000..6ac0766f4 --- /dev/null +++ b/patrons/vuemastery.svg @@ -0,0 +1,36 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/patrons/zenarchitects.png b/patrons/zenarchitects.png new file mode 100644 index 000000000..a5f836fe5 Binary files /dev/null and b/patrons/zenarchitects.png differ diff --git a/pt/api/index.html b/pt/api/index.html new file mode 100644 index 000000000..eb9fd0dc9 --- /dev/null +++ b/pt/api/index.html @@ -0,0 +1,179 @@ + + + + + + API Referência | Vue I18n + + + + + + + + + +

# API Referência

# Estendendo o protótipo Vue

# Opções do construtor Vue

# i18n

  • Tipo: I18nOptions

Opção de localização baseada em componentes.

  • Veja também: Opções do construtor VueI18n

# Métodos injetados no Vue

# $t

  • Argumentos:

    • {Path} key: obrigatório
    • {Locale} locale: opcional
    • {Array | Object} values: opcional
  • Retorno: TranslateResult

Obtendo uma mensagem traduzida usando a chave key. As mensagens de localização em um componente têm precedência sobre as mensagens globais. Se não houver mensagens de localização no componente, a localização será executada usando as mensagens de localização globais. Se locale for especificado, as mensagens de localização do locale serão usadas. Se key foi especificada para a lista / formato nomeado das mensagens de localização, então os values também devem ser especificados. Você pode aprender mais sobre values na seção Formato das mensagens de localização.

Dica

Observe que você precisa garantir este contexto igual à instância do componente nos métodos em seu ciclo de vida (por exemplo, nas opções de data,const $t = this.$t.bind(this)).

# $tc

  • Argumentos:

    • {Path} key: obrigatório
    • {number} choice: opcional, padrão 1
    • {Locale} locale: opcional
    • {string | Array | Object} values: opcional
  • Retorno: TranslateResult

Obtendo uma mensagem traduzida usando a key com pluralização. As mensagens de localização de componentes têm precedência sobre as mensagens globais. Se não houver mensagens de localização no componente, a localização será executada usando mensagens de localização globais. Se locale for especificado, as mensagens de localização de locale serão usadas. Se um valor de texto for especificado para value, a localização será realizada para esse valor. Se for um Array ou Object especificado em value, então deve ser especificado com value de $t.

Se a implementação de pluralização padrão não for adequada para você, consulte regras de pluralização nas opções do construtor e pluralização customizada.

Dica

Observe que você precisa garantir este contexto igual à instância do componente nos métodos em seu ciclo de vida (por exemplo, nas opções de data, const $tc = this.$tc.bind(this)).

# $te

  • Argumentos:

    • {Path} key: obrigatório
    • {Locale} locale: opcional
  • Retorno: boolean

Verifica se existe uma tradução para uma chave nas mensagens de localização. Se não houver mensagens de localização no componente, ele verifica as mensagens de localização globais. Se locale for especificado, então a presença de locale nas mensagens é verificada.

Dica

Observe que você precisa garantir este contexto igual à instância do componente nos métodos em seu ciclo de vida (por exemplo, nas opções de data, const $te = this.$te.bind(this)).

# $d

🆕 Adicionado na versão 7.0+

  • Argumentos:

    • {number | Date} value: obrigatório
    • {Path | Object} key: opcional
    • {Locale | Object} locale: opcional
  • Retorno: DateTimeFormatResult

Localização da data e hora de value com o formato de data e hora de key. O formato de data e hora da key precisa ser registrado na opção dateTimeFormats da classe VueI18n, e depende da opção locale do construtor VueI18n. Se você especificar o argumento locale, ele terá prioridade sobre a opção locale do construtor VueI18n.

Se o formato de data para key não estiver na opção dateTimeFormats, então um formato de fallback será usado com base na opção fallbackLocale do construtor VueI18n.

Dica

Observe que você precisa garantir este contexto igual à instância do componente nos métodos em seu ciclo de vida (por exemplo, nas opções de data, const $d = this.$d.bind(this)).

# $n

🆕 Adicionado na versão 7.0+

  • Argumentos:

    • {number} value: obrigatório
    • {Path | Object} format: opcional
    • {Locale} locale: opcional
  • Retorno: NumberFormatResult

Localização do número value usando o formato de número format. O formato de número de format deve ser registrado na opção numberFormats da classe VueI18n, e depende da opção locale do construtor VueI18n. Especificar o argumento locale sobrescreve a opção locale do construtor VueI18n.

Se o formato de número para format não for especificado na opção numberFormats, um formato de fallback será usado com base na opção fallbackLocale do construtor VueI18n.

Se o segundo argumento para format for especificado por um objeto, ele deverá conter as seguintes propriedades:

  • key {Path}: opcional, número formatado
  • locale {Locale}: opcional, localização
  • compactDisplay {string}: opcional, opção de formatação do número
  • currency {string}: opcional, opção de formatação do número
  • currencyDisplay {string}: opcional, opção de formatação do número
  • currencySign {string}: opcional, opção de formatação do número
  • localeMatcher {string}: opcional, opção de formatação do número
  • notation {string}: opcional, opção de formatação do número
  • numberingSystem {string}: opcional, opção de formatação do número
  • signDisplay {string}: opcional, opção de formatação do número
  • style {string}: opcional, opção de formatação do número
  • unit {string}: opcional, opção de formatação do número
  • unitDisplay {string}: opcional, opção de formatação do número
  • useGrouping {boolean}: opcional, opção de formatação do número
  • minimumIntegerDigits {string}: opcional, opção de formatação do número
  • minimumFractionDigits {string}: opcional, opção de formatação do número
  • maximumFractionDigits {string}: opcional, opção de formatação do número
  • minimumSignificantDigits {string}: opcional, opção de formatação do número
  • maximumSignificantDigits {string}: opcional, opção de formatação do número

Qualquer opções de formatação de número especificadas terão precedência sobre os valores numberFormats do construtor VueI18n.

Dica

Observe que você precisa garantir este contexto igual à instância do componente nos métodos em seu ciclo de vida (por exemplo, nas opções de data, const $n = this.$n.bind(this)).

# Propriedades injetadas

# $i18n

  • Tipo: I18n

  • Somente leitura

Obter uma instância de VueI18n, se definido.

Se você especificou uma opção i18n nas opções do componente, você será capaz de obter uma instânciaVueI18n no componente, caso contrário, você poderá obter a instância raiz VueI18n.

# A classe VueI18n

A classe VueI18n implementa a interface I18n de definições de tipo de fluxo (opens new window)

# Propriedades estáticas

# version

  • Tipo: string

Versão vue-i18n.

# availabilities

🆕 Adicionado na versão 7.0+

  • Tipo: IntlAvailability

Verificar a disponibilidade dos seguintes recursos de internacionalização:

  • {boolean} dateTimeFormat: formatação de data sensível à localidade

  • {boolean} numberFormat: formatação de número sensível à localidade

Os recursos de internacionalização acima dependem do ambiente do navegador (opens new window), que implementa a API de internacionalização ECMAScript (ECMA-402).

# Opções de construtor

É possível especificar algumas das opções do construtor I18nOptions com base em definições de tipo de fluxo (opens new window)

# locale

  • Tipo: Locale

  • Padrão: 'en-US'

O local usado para localização. Se uma localidade contém território e dialeto, esta localidade contém um fallback implícito.

# fallbackLocale

  • Tipo: FallbackLocale

  • Padrão: false

Localidade reserva para localização. Para obter mais detalhes e definições de fallback mais complexos, consulte a seção fallback.

# messages

  • Tipo: LocaleMessages

  • Padrão: {}

Mensagens de localização para o local.

# dateTimeFormats

🆕 Adicionado na versão 7.0+

  • Tipo: DateTimeFormats

  • Padrão: {}

Formatos de data para localização.

# numberFormats

🆕 Adicionado na versão 7.0+

  • Tipo: NumberFormats

  • Padrão: {}

Formatos de número para localização.

# availableLocales

🆕 Adicionado na versão 8.9.0+

  • Tipo: Locale[]

  • Padrão: []

  • Exemplos: ["en", "ru"]

Lista de localidades disponíveis em messages em ordem lexical.

# formatter

  • Tipo: Formatter

  • Padrão: Formatador integrado

Um método de formatação que implementa a interface Formatter.

# modifiers

🆕 Adicionado na versão 8.15.0+

  • Tipo: Modifiers

  • Padrão: modificadores lower e upper

Funções modificadoras para mensagens relacionadas

# missing

  • Tipo: MissingHandler

  • Padrão: null

Manipulador para mensagens de localização ausentes. O manipulador será chamado com locale, a key da mensagem de localização e os values.

Se este manipulador for especificado e for feita uma tentativa de acessar a mensagem de localização ausente, não haverá nenhum aviso no console.

# fallbackRoot

  • Tipo: Boolean

  • Padrão: true

Ao usar a localização em componentes, determina se deve consultar a localização de nível raiz (global) quando no caso da localização falhar.

Se definido como false, um aviso será lançado e uma chave retornada.

# fallbackRootWithEmptyString

🆕 Adicionado na versão 8.26+

  • Tipo: Boolean

  • Padrão: true

Na localização do componente, se deve retornar à localização de nível raiz (global) quando a mensagem local for uma string vazia.

Por favor, note que o comportamento padrão no vue-i18n 9.x é não voltar ao root para a mensagem local que é uma string vazia.

Se for false, a mensagem local vazia não retornará ao root e será mantida como string vazia.

# sync

  • Tipo: Boolean

  • Padrão: true

Se sincroniza a localidade de nível raiz com a localidade de localização do componente.

Se o valor for false, independentemente da localidade definida no nível raiz, a localidade definida no componente será usada.

# silentTranslationWarn

6.1+, 🆙 8.13

  • Tipo: Boolean | RegExp

  • Padrão: false

Desativa os avisos exibidos quando a localização falha.

Se verdadeiro, desativa os avisos de erro de localização. Se você usar uma expressão regular, você pode desligar os avisos de erro que correspondem à key (por exemplo, $t).

# silentFallbackWarn

🆕 Adicionado na versão 8.8+, 🆙 8.13

  • Tipo: Boolean | RegExp

  • Padrão: false

Desative os avisos ao retornar para fallback de fallbackLocale ou root.

Se true, os avisos serão gerados apenas quando nenhuma tradução estiver disponível, e não para os casos de fallbacks. +Se você usar uma expressão regular, poderá suprimir os avisos de fallback que correspondem à chave (por exemplo, $t).

# pluralizationRules

8.5+

  • Tipo: PluralizationRules

  • Padrão: {}

Um conjunto de regras para pluralização de palavras no seguinte formato:

  {
+    // Chave - a localidade para a qual a regra será aplicada.
+    // Valor - uma função para obter o índice da opção de pluralização a partir do número atual e o número especificado de opções. (Veja a função getChoiceIndex)
+    'pt': function(choice, choiceIndex) => Number/* índice da palavra em plural */;
+    'ru': function(choice, choiceIndex) => Number/* índice da palavra em plural */;
+    'en': function(choice, choiceIndex) => Number/* índice da palavra em plural */;
+    'jp': function(choice, choiceIndex) => Number/* índice da palavra em plural */;
+  }
+

# preserveDirectiveContent

Adicionado na versão 8.7+

  • Tipo: Boolean

  • Padrão: false

Determina se o elemento da diretiva v-t deve reter o textContent após a diretiva ser removida do elemento.

# warnHtmlInMessage

Adicionado na versão 8.11+

  • Tipo: WarnHtmlInMessageLevel

  • Padrão: off

Permitir ou não o uso de formatação HTML em mensagens de localização. Veja também a propriedade warnHtmlInMessage.

Atenção!

A partir da próxima versão principal, o valor padrão warnHtmlInMessage será warn.

# sharedMessages

Adicionado na versão 8.12+

  • Tipo: LocaleMessages

  • Padrão: undefined

Mensagens de localização comuns quando localizadas em componentes. Ver localização baseada em componentes para mais detalhes.

# postTranslation

Adicionado na versão 8.16+

  • Tipo: PostTranslationHandler

  • Padrão: null

Um manipulador para pós-processamento da tradução. Executado após chamar $t, t, $tc e tc.

Pode ser útil se você precisar processar adicionalmente o texto final da tradução, por exemplo, para eliminar os espaços e cortes de espaçamento.

# componentInstanceCreatedListener

Adicionado na versão 8.18+

  • Tipo: ComponentInstanceCreatedListener

  • Padrão: null

Um manipulador para receber uma notificação sobre a criação de uma instância local de um componente. O manipulador é chamado com instâncias VueI18n novas e antigas (raiz).

Este manipulador é útil ao estender a instância raiz do VueI18n e se deseja aplicar também essas extensões à instância local do componente.

# escapeParameterHtml

Adicionado na versão 8.22+

  • Tipo: Boolean

  • Padrão: false

Se escapeParameterHtml for definido como true, os parâmetros de interpolação serão escapados antes que a mensagem seja traduzida. Isso é útil quando o resultado da tradução é usado em v-html e o texto a ser traduzido contém marcação HTML (por exemplo, <b> em torno de um valor fornecido pelo usuário). Este padrão destina-se principalmente a casos em que strings de texto pré-compiladas para componentes de IU.

O processo de escape envolve a substituição dos seguintes símbolos por suas respectivas entidades de caracteres HTML: <, >, ", '.

Definir escapeParameterHtml como true não deve quebrar a funcionalidade existente, mas fornecerá proteção contra vetores de ataque XSS.

# Propriedades

# locale

  • Tipo: Locale

  • Leitura/Escrita

O local usado para localização. Se uma localidade contém um território e um dialeto, essa localidade contém um fallback implícito.

# fallbackLocale

  • Tipo: FallbackLocale

  • Leitura/Escrita

O local usado para localização de fallback. Para obter mais definições de fallback, consulte a seção [fallback](../ guide/fallback.md).

# messages

  • Tipo: LocaleMessages

  • Somente leitura

As mensagens de localização usadas para a localização da tradução.

# dateTimeFormats

🆕 Adicionado na versão 7.0+

  • Tipo: DateTimeFormats

  • Somente leitura

Formatação de data para localização.

# numberFormats

🆕 Adicionado na versão 7.0+

  • Tipo: NumberFormats

  • Somente leitura

Os formatos para formatação de números da localização.

# missing

  • Tipo: MissingHandler

  • Leitura/Escrita

Manipulador para chaves de localização ausentes.

# formatter

  • Tipo: Formatter

  • Leitura/Escrita

Um método de formatação que implementa a interface Formatter.

# silentTranslationWarn

6.1+, 🆙 8.13

  • Tipo: Boolean | RegExp

  • Leitura/Escrita

Desative os avisos exibidos em erros de localização.

# silentFallbackWarn

🆕 Adicionado na versão 8.8+, 🆙 8.13

  • Tipo: Boolean | RegExp

  • Leitura/Escrita

Desative os avisos de fallback quando a localização falha.

# pluralizationRules

8.5+

  • Tipo: PluralizationRules

  • Leitura/Escrita

Um conjunto de regras de pluralização dependentes da localidade.

# preserveDirectiveContent

Adicionado na versão 8.7+

  • Tipo: Boolean

  • Leitura/Escrita

Se o elemento da diretiva v-t deve preservar o textContent após a diretiva ser removida do elemento.

# warnHtmlInMessage

Adicionado na versão 8.11+

  • Tipo: WarnHtmlInMessageLevel

  • Leitura/Escrita

Permitir ou não o uso de formatação HTML em mensagens de localização.

Se você definir warn ou error, irá verificar as mensagens de localidade na instância VueI18n.

Se você definir warn um aviso será gerado no console.

Se você definir error gera o erro.

O valor padrão na instância VueI18n é definido como off.

# postTranslation

Adicionado na versão 8.16+

  • Tipo: PostTranslationHandler

  • Leitura/Escrita

Um manipulador para o pós-processamento da tradução.

# Métodos

# getChoiceIndex

  • Argumentos:

    • {number} choice
    • {number} choicesLength
  • Retorno: finalChoice {number}

Obter um índice para pluralizar o número atual e o número de opções fornecido. +A implementação pode ser substituída pela mutação do protótipo:

VueI18n.prototype.getChoiceIndex = /* implementação personalizada */
+

No entanto, na maioria dos casos, é suficiente passar a função desejada para a opção do construtor pluralizationRules.

# getLocaleMessage( locale )

  • Argumentos:

    • {Locale} locale
  • Retorno: LocaleMessageObject

Obtendo a mensagem da localidade.

# setLocaleMessage( locale, message )

  • Argumentos:

    • {Locale} locale
    • {LocaleMessageObject} message

Defina a mensagem de localidade.

NOTA

Adicionado na versão 8.11+

Se você definir warn ou error na propriedade warnHtmlInMessage, quando este método for executado, ele irá verificar se a formatação HTML é usada para mensagem local.

# mergeLocaleMessage( locale, message )

6.1+

  • Argumentos:

    • {Locale} locale
    • {LocaleMessageObject} message

Mesclar as mensagens de localidade registradas com a mensagem de localidade.

NOTA

Adicionado na versão 8.11+

Se você definir warn ou error na propriedade warnHtmlInMessage, quando este método for executado, ele irá verificar se a formatação HTML é usada para mensagem local.

# t( key, [locale], [values] )

  • Argumentos:

    • {Path} key: obrigatório
    • {Locale} locale: opcional
    • {Array | Object} values: opcional
  • Retorno: : TranslateResult

Semelhante à função retornada pelo método $t. Veja $t para detalhes.

# tc( key, [choice], [values] )

  • Argumentos:

    • {Path} key: obrigatório
    • {number} choice: opcional, padrão 1
    • {string | Array | Object} values: opcional
  • Retorno: TranslateResult

Semelhante à função retornada pelo método $tc. Veja $tc para detalhes.

# te( key, [locale] )

  • Argumentos:

    • {string} key: obrigatório
    • {Locale} locale: opcional
  • Retorno: boolean

Verifica se a chave especificada existe nas mensagens de localização global. Se você especificar locale, a verificação será feita nas mensagens de locale.

# getDateTimeFormat ( locale )

🆕 Adicionado na versão 7.0+

  • Argumentos:

    • {Locale} locale
  • Retorno: DateTimeFormat

Obtenha o formato de data e hora do local.

# setDateTimeFormat ( locale, format )

🆕 Adicionado na versão 7.0+

  • Argumentos:

    • {Locale} locale
    • {DateTimeFormat} format

Configurando formatos de formatação de data para localização.

# mergeDateTimeFormat ( locale, format )

🆕 Adicionado na versão 7.0+

  • Argumentos:

    • {Locale} locale
    • {DateTimeFormat} format

Mescle os formatos de data e hora registrados com o formato de data e hora do local.

# d( value, [key], [locale] )

🆕 Adicionado na versão 7.0+

  • Argumentos:

    • {number | Date} value: obrigatório
    • {Path | Object} key: opcional
    • {Locale | Object} locale: opcional
  • Retorno: DateTimeFormatResult

Semelhante à função retornada pelo método $d. Veja $d para detalhes.

# getNumberFormat ( locale )

🆕 Adicionado na versão 7.0+

  • Argumentos:

    • {Locale} locale
  • Retorno: NumberFormat

Obtenha o formato de número da localidade.

# setNumberFormat ( locale, format )

🆕 Adicionado na versão 7.0+

  • Argumentos:

    • {Locale} locale
    • {NumberFormat} format

Defina o formato de número do local.

# mergeNumberFormat ( locale, format )

🆕 Adicionado na versão 7.0+

  • Argumentos:

    • {Locale} locale
    • {NumberFormat} format

Mescle os formatos de número registrados com o formato de número do local.

# n( value, [format], [locale] )

🆕 Adicionado na versão 7.0+

  • Argumentos:

    • {number} value: obrigatório
    • {Path | Object} format: opcional
    • {Locale} locale: opcional
  • Retorno: NumberFormatResult

Semelhante à função retornada pelo método $n. Veja $n para detalhes.

# Diretivas

🆕 Adicionado na versão 7.3+

# v-t

  • Aguarda: string | Object

  • Modificadores:

    • .preserve: (8.7.0+) preserva o textContent de um elemento quando a diretiva é desvinculada.
  • Detalhes:

Atualizar o textContent de um elemento que foi traduzido usando mensagens de localização. Você pode usar string ou sintaxe de objeto. A sintaxe da string pode ser especificada como o caminho para a mensagem de localização. Ao usar a sintaxe de objeto, você deve especificar as seguintes propriedades:

  • path: obrigatório, chave da mensagem de localização
  • locale: opcional, localização
  • args: opcional, para lista ou formatação nomeada

NOTA

O elemento textContent será limpo por padrão quando a diretiva v-t for desassociada. Isso pode ser uma situação indesejável quando usado dentro de transições (opens new window). Para preservar os dados textContent após a desvinculação da diretiva, use o modificador .preserve ou a opção global preserveDirectiveContent.

  • Exemplos:
<!-- sintaxe de string: literal -->
+<p v-t="'foo.bar'"></p>
+
+<!-- sintaxe de string: vinculação por meio de dados ou props computados -->
+<p v-t="msg"></p>
+
+<!-- sintaxe do objeto: literal -->
+<p v-t="{ path: 'hi', locale: 'pt', args: { name: 'kazupon' } }"></p>
+
+<!-- sintaxe do objeto: ligação por meio de dados ou props computados -->
+<p v-t="{ path: greeting, args: { name: fullName } }"></p>
+
+<!-- com o modificador de preservação -->
+<p v-t.preserve="'foo.bar'"></p>
+

# Componentes

# Componente funcional i18n

🆕 Adicionado na versão 7.0+

# Props:

  • path {Path}: obrigatório, caminho-chave de mensagens de localização
  • locale {Locale}: opcional, localização
  • tag {string | boolean | Object}: opcional, padrão 'span'
  • places {Array | Object}: opcional (7.2+)

Atenção!

A partir da próxima versão principal, a opção places será removida. Use a sintaxe de slot.

# Usando:

<div id="app">
+  <!-- ... -->
+  <i18n path="term" tag="label" for="tos">
+    <a :href="url" target="_blank">{{ $t('tos') }}</a>
+  </i18n>
+  <!-- ... -->
+</div>
+
const messages = {
+  en: {
+    tos: 'Term of Service',
+    term: 'I accept xxx {0}.'
+  },
+  pt: {
+    tos: 'Termos de serviço',
+    term: 'Eu concordo xxx {0}'.
+  }
+}
+
+const i18n = new VueI18n({
+  locale: 'en',
+  messages
+})
+new Vue({
+  i18n,
+  data: {
+    url: '/term'
+  }
+}).$mount('#app')
+

# Veja também:

Componente de interpolação

# Componente funcional i18n-n

🆕 Adicionado na versão 8.10+

# Props:

  • value {number}: obrigatório, número para formatar
  • format {string | NumberFormatOptions}: opcional, nome de formato de número ou objeto com opções de formato explícito
  • locale {Locale}: opcional, localização
  • tag {string | boolean | Object}: opcional, padrão 'span'

# Usando:

<div id="app">
+  <!-- ... -->
+  <i18n-n :value="money" format="currency" tag="label">
+    <span v-slot:currency="slotProps" class="font-weight: bold">
+      {{ slotProps.currency }}
+    <span>
+  </i18n-n>
+  <!-- ... -->
+</div>
+
var numberFormats = {
+  'en-US': {
+    currency: {
+      style: 'currency',
+      currency: 'USD'
+    }
+  },
+  'pt-BR': {
+    currency: {
+      style: 'currency',
+      currency: 'BRL'
+    }
+  }
+}
+
+const i18n = new VueI18n({
+  locale: 'en-US',
+  numberFormats
+})
+
+new Vue({
+  i18n,
+  data: {
+    money: 10234
+  }
+}).$mount('#app')
+

# Slots com escopo

O componente funcional <i18n-n> pode aceitar vários slots com escopo nomeado. A lista de nomes de slots suportados é baseada nos [Intl.NumberFormat.formatToParts() tipos de saída] (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NumberFormat/formatToParts):

  • currency
  • decimal
  • fraction
  • group
  • infinity
  • integer
  • literal
  • minusSign
  • nan
  • plusSign
  • percentSign

Cada um desses slots com escopo nomeado aceitará três parâmetros de escopo:

  • [slotName] {FormattedNumberPartType}: parâmetro com o mesmo nome do nome do slot real (como integer)
  • index {Number}: índice da parte específica na matriz de partes numéricas
  • parts {Array}: array de todas as partes numéricas formatadas

# Veja também:

Formatação personalizada de números

# Atributos especiais

# place

🆕 Adicionado na versão 7.2+

# Aguarda: {number | string}

Usado ao interpolar um componente para especificar um índice para formatação de lista ou uma chave para formatação nomeada.

Mais sobre o uso na seção do link abaixo.

# Veja também:

Componente de interpolação

+ + + diff --git a/pt/guide/component.html b/pt/guide/component.html new file mode 100644 index 000000000..2158da58f --- /dev/null +++ b/pt/guide/component.html @@ -0,0 +1,195 @@ + + + + + + Localização baseada em componentes | Vue I18n + + + + + + + + + +

# Localização baseada em componentes

Em geral, as informações de localidade (por exemplo, locale, messages, etc) são definidas como opção de construtor na instância VueI18n e define a opção i18n como a instância raiz do Vue.

Portanto, você pode realizar traduções globalmente usando os métodos $t ou $tc na instância raiz do Vue e qualquer um dos componentes nela. Mas também é possível especificar dados para localização em cada componente separadamente, o que pode ser mais conveniente devido ao design orientado a componentes.

Um exemplo de localização baseada em componente:

// Definir a localização para raiz na instância Vue
+const i18n = new VueI18n({
+  locale: 'pt',
+  messages: {
+    en: {
+      message: {
+        hello: 'Hello World',
+        greeting: 'Good morning'
+      }
+    },
+    pt: {
+      message: {
+        hello: 'Olá Mundo',
+        greeting: 'Bom dia'
+      }
+    }
+  }
+})
+
+// Definição no componente
+const Component1 = {
+  template: `
+    <div class="container">
+     <p>Component1 locale messages: {{ $t("message.hello") }}</p>
+     <p>Fallback global locale messages: {{ $t("message.greeting") }}</p>
+   </div>`,
+  i18n: {
+    // opção `i18n` definindo dados de localização para o componente
+    messages: {
+      en: { message: { hello: 'hello component1' } },
+      pt: { message: { hello: 'olá componente1' } }
+    }
+  }
+}
+
+new Vue({
+  i18n,
+  components: {
+    Component1
+  }
+}).$mount('#app')
+

Template:

<div id="app">
+  <p>{{ $t("message.hello") }}</p>
+  <component1></component1>
+</div>
+

O resultado será o seguinte:

<div id="app">
+  <p>Olá Mundo</p>
+  <div class="container">
+    <p>Component1 locale messages: olá component1</p>
+    <p>Fallback global locale messages: Bom dia</p>
+  </div>
+</div>
+

Como no exemplo acima, se o componente não tiver a mensagem de localidade, ele retornará às informações de localização definidas globalmente. O componente usa o idioma definido na instância raiz (no exemplo acima: locale: 'ja').

Observe que, por padrão, ao acessar os dados de localização da raiz, avisos serão gerados no console:

[vue-i18n] Value of key 'message.greeting' is not a string!
+[vue-i18n] Fall back to translate the keypath 'message.greeting' with root locale.
+

Para ocultar esses avisos (deixando aqueles que alertam sobre a falta completa de tradução para a chave fornecida), defina a opção silentFallbackWarn: true ao inicializar a instância do VueI18n.

Se você precisar traduzir com base na localidade do componente, pode fazê-lo usando as opções sync: false e locale na propriedade do i18n.

# Mensagens de localização comuns para componentes

Às vezes, você pode querer importar as mensagens de localidade compartilhadas para determinados componentes, não o fallback de mensagens na localidade global (por exemplo, mensagens comuns de determinado recurso para componentes.

Para fazer isso, você pode usar a opção sharedMessages na propriedade i18n do componente.

Um exemplo de uso de mensagens de localização comuns:

export default {
+  en: {
+    buttons: {
+      save: 'Save'
+      // ...
+    }
+  },
+  pt: {
+    buttons: {
+      save: 'Salvar'
+      // ...
+    }
+  }
+}
+

Componente:

import commonMessage from './locales/common' // importação de mensagens da localidade em comum
+
+export default {
+  name: 'ServiceModal',
+  template: `
+    <div class="modal">
+      <div class="body">
+        <p>Este é um bom serviço</p>
+      </div>
+      <div class="footer">
+        <button type="button">
+          {{ $t('buttons.save') }}
+        </button>
+      </div>
+    </div>
+  `,
+  i18n: {
+    messages: { ... },
+    sharedMessages: commonMessages
+  }
+}
+

Se as opções sharedMessages e messages forem especificadas, então suas mensagens serão mescladas em mensagens de localização na instância VueI18n deste componente.

# Localização em componentes funcionais

Ao usar um componente funcional, todos os dados (incluindo props, children, slots, parent, etc.) são passados ​​através do context, que contém todos esses atributos. Além disso, não é possível usar this, então ao usar vue-i18n com componentes funcionais, você deve se referir a $t como parent.$t, assim:

...
+<div>
+  <a href="#" target="_blank" rel="noopener noreferrer">
+    <img src="./assets/example.jpg" :alt="parent.$t('message.hello')" />
+  </a>
+</div>
+...
+
+ + + diff --git a/pt/guide/datetime.html b/pt/guide/datetime.html new file mode 100644 index 000000000..27d05cde0 --- /dev/null +++ b/pt/guide/datetime.html @@ -0,0 +1,147 @@ + + + + + + Localização de datas | Vue I18n + + + + + + + + + +

# Localização de datas

Suporta a versão

🆕 7.0+

Você pode localizar datas de acordo com o formato apropriado.

Formato de exemplo para DateTime:

const dateTimeFormats = {
+  'en-US': {
+    short: {
+      year: 'numeric',
+      month: 'short',
+      day: 'numeric'
+    },
+    long: {
+      year: 'numeric',
+      month: 'long',
+      day: 'numeric',
+      weekday: 'long',
+      hour: 'numeric',
+      minute: 'numeric'
+    }
+  },
+  'pt-BR': {
+    short: {
+      year: 'numeric',
+      month: 'short',
+      day: 'numeric'
+    },
+    long: {
+      year: 'numeric',
+      month: 'long',
+      day: 'numeric',
+      weekday: 'long',
+      hour: 'numeric',
+      minute: 'numeric',
+      hour12: true
+    }
+  }
+}
+

Como visto acima, é possível definir um formato de data nomeado (por exemplo, short, long, etc.) usando opções ECMA-402 Intl.DateTimeFormat (opens new window)

Depois disso, para poder usar este formato em mensagens de localização, você deve definir a opção dateTimeFormats no construtor na instância VueI18n:

const i18n = new VueI18n({
+  dateTimeFormats
+})
+
+new Vue({
+  i18n
+}).$mount('#app')
+

Template:

<div id="app">
+  <p>{{ $d(new Date(), 'short') }}</p>
+  <p>{{ $d(new Date(), 'long', 'pt-BR') }}</p>
+</div>
+

O resultado será o seguinte:

<div id="app">
+  <p>Jan 18, 2021</p>
+  <p>domingo, 18 de janeiro de 2021 5:49 AM</p>
+</div>
+
+ + + diff --git a/pt/guide/directive.html b/pt/guide/directive.html new file mode 100644 index 000000000..3ae02d04c --- /dev/null +++ b/pt/guide/directive.html @@ -0,0 +1,173 @@ + + + + + + Diretiva personalizada | Vue I18n + + + + + + + + + +

# Diretiva personalizada

Suporta a versão

🆕 7.3+

As traduções podem ser feitas não apenas usando a diretiva v-t personalizada, mas também usando o método $t.

# Sintaxe de string

Você pode passar o keypath de mensagens da localização como uma string.

JavaScript:

new Vue({
+  i18n: new VueI18n({
+    locale: 'en',
+    messages: {
+      en: { hello: 'Hi there!' },
+      pt: { hello: 'Olá!' }
+    }
+  }),
+  data: { path: 'hello' }
+}).$mount('#string-syntax')
+

Template:

<div id="string-syntax">
+  <!-- string literal -->
+  <p v-t="'hello'"></p>
+  <!-- ligação do keypath por meio dos dados -->
+  <p v-t="path"></p>
+</div>
+

O resultado será o seguinte:

<div id="string-syntax">
+  <p>Olá!</p>
+  <p>Olá!</p>
+</div>
+

# Sintaxe do objeto

Você pode usar a sintaxe do objeto.

JavaScript:

new Vue({
+  i18n: new VueI18n({
+    locale: 'en',
+    messages: {
+      en: { hello: 'Hi {name}!' },
+      pt: { hello: 'Olá {name}!' }
+    }
+  }),
+  computed: {
+    nickName() { return 'kazupon' }
+  },
+  data: { path: 'hello' }
+}).$mount('#object-syntax')
+

Template:

<div id="object-syntax">
+  <!-- literal -->
+  <p v-t="{ path: 'hello', locale: 'pt', args: { name: 'kazupon' } }"></p>
+  <!-- ligação do keypath por meio dos dados  -->
+  <p v-t="{ path: path, args: { name: nickName } }"></p>
+</div>
+

O resultado será o seguinte:

<div id="object-syntax">
+  <p>Olá kazupon!</p>
+  <p>Hi kazupon!</p>
+</div>
+

# Use com transições

Suporta a versão

🆕 8.7+

Ao usar a diretiva v-t em um elemento dentro do componente <transition> (opens new window), você pode ver como a mensagem traduzida desaparece durante a animação de transição. Este comportamento é devido à implementação do próprio componente <transition> - todas as diretivas no elemento que desaparece dentro do componente <transition> devem ser destruídas antes do início da transição. Esse comportamento pode resultar em oscilação do conteúdo em animações curtas, mas é mais perceptível em animações de transição longa.

Para preservar o conteúdo de uma diretiva durante uma animação de transição, você precisa adicionar modificador .preserve ao definir a diretiva v-t.

Javascript:

new Vue({
+  i18n: new VueI18n({
+    locale: 'pt',
+    messages: {
+      pt: { preserve: 'com preservação' }
+    }
+  }),
+  data: { toggle: true }
+}).$mount('#in-transitions')
+

Template:

<div id="in-transitions">
+  <transition name="fade">
+    <span v-if="toggle" v-t.preserve="'preserve'"></span>
+  </transition>
+  <button @click="toggle = !toggle">Toggle</button>
+</div>
+

Também é possível definir globalmente a configuração preserveDirectiveContent na instância VueI18n, o que afetará todas as diretivas v-t sem adicionar um modificador.

JavaScript:

new Vue({
+  i18n: new VueI18n({
+    locale: 'pt',
+    messages: {
+      pt: { preserve: 'com preservação' }
+    },
+    preserveDirectiveContent: true
+  }),
+  data: { toggle: true }
+}).$mount('#in-transitions')
+

Template:

<div id="in-transitions">
+  <transition name="fade">
+    <span v-if="toggle" v-t="'preserve'"></span>
+  </transition>
+  <button @click="toggle = !toggle">Toggle</button>
+</div>
+

Você pode aprender mais sobre os exemplos acima [aqui] (https://github.com/kazupon/vue-i18n/tree/dev/examples/directive)

# $t ou v-t

# $t

$t é um método adicionado à instância Vue. Tem os seguintes prós e contras:

# Prós

Você pode flexivelmente usar a sintaxe de chaves {{}} em templates e também props e métodos computados na instância Vue.

# Contras

$t é executado toda vez quando ocorre uma nova renderização, então tem a sobrecarga de fazer a tradução.

# v-t

v-t é uma diretiva personalizada. Tem os seguintes prós e contras:

# Prós

v-t tem melhor desempenho do que o método $t devido ao seu cache com a diretiva personalizada, quando traduzido uma vez. Além disso, a pré-tradução é possível com o módulo do compilador Vue que foi fornecido por vue-i18n-extensions (opens new window).

Portanto, é possível fazer mais otimizações de desempenho.

# Contras

v-t não pode ser usado de forma tão flexível como $t, e isso adiciona complexidade. A tradução com v-t é inserida no textContent do elemento. Além disso, ao usar a renderização do lado do servidor, você precisa definir a diretiva personalizada (opens new window) por meio da opção directives da função createRenderer.

+ + + diff --git a/pt/guide/fallback.html b/pt/guide/fallback.html new file mode 100644 index 000000000..e45a2ea23 --- /dev/null +++ b/pt/guide/fallback.html @@ -0,0 +1,146 @@ + + + + + + Fallback Localização | Vue I18n + + + + + + + + + +

# Fallback Localização

Resumo: Use fallbackLocale: '<lang>' para escolher qual idioma usar quando seu idioma preferido não tiver uma tradução.

# Fallback implícito usando localidades

Se um locale é fornecido contendo um território e um dialeto opcional, o fallback implícito é ativado automaticamente.

Por exemplo, para de-DE-bavarian o seguinte será considerado como fallback:

  1. de-DE-bavarian
  2. de-DE
  3. de

Para desativar a detecção automática de locais de fallback, especifique o caractere !, Por exemplo, de-DE!

# Fallback explícito com um local

Às vezes, alguns itens não são traduzidas para outros idiomas. Neste exemplo, o item hello está disponível no idioma inglês, mas não no português:

const messages = {
+  en: {
+    hello: 'Hello, world!'
+  },
+  pt: {
+    // Localização sem tradução para `hello`
+  }
+}
+

Se você deseja usar (digamos) mensagens de localização de en, quando a tradução não está na localização desejada, você deve defina a opção fallbackLocale ao inicializar a instância VueI18n:

const i18n = new VueI18n({
+  locale: 'pt',
+  fallbackLocale: 'en',
+  messages
+})
+

Template:

<p>{{ $t('hello') }}</p>
+

O resultado será o seguinte:

<p>Hello, world!</p>
+

Por padrão, se as mensagens de localização de fallback de fallbackLocale foram usadas, os avisos serão exibidos no console:

[vue-i18n] Value of key 'hello' is not a string!
+[vue-i18n] Fall back to translate the keypath 'hello' with 'en' locale.
+

Para ocultar esses avisos (deixando aqueles em casos em que não há traduções para a chave fornecida), defina silentFallbackWarn: true ao inicializar a instância VueI18n.

# Fallback explícito com um array de localidades

Você pode especificar mais de um local de fallback usando um array.

Por exemplo:

fallbackLocale: ['pt', 'en'],
+

# Fallback explícito com mapas de decisão

Um algoritmo de tomada de decisão mais complexo para determinar o local de fallback pode ser implementado usando mapas de decisão com localidades em um fallback de acordo.

Por exemplo, usando o seguinte mapa de decisão

fallbackLocale: {
+  /* 1 */ 'de-CH':   ['fr', 'it'],
+  /* 2 */ 'zh-Hant': ['zh-Hans'],
+  /* 3 */ 'es-CL':   ['es-AR'],
+  /* 4 */ 'es':      ['en-GB'],
+  /* 5 */ 'pt':      ['es-AR'],
+  /* 6 */ 'default': ['en', 'ru']
+},
+

Resultará nas seguintes cadeias de fallback

Local fallback escolha
'de-CH' de-CH > fr > it > en > ru
'de' de > en > ru
'zh-Hant' zh-Hant > zh-Hans > zh > en > ru
'es-SP' es-SP > es > en-GB > en > ru
'es-SP!' es-SP > en > ru
'fr' fr > en > ru
'pt-BR' pt-BR > pt > es-AR > es > en-GB > en > ru
'es-CL' es-CL > es-AR > es > en-GB > en > ru

# Fallback interpolação

  • Resumo: Defina formatFallbackMessages: true para fazer a interpolação do modelo nas chaves de tradução quando seu idioma não tiver uma tradução para uma chave. *

Como as chaves para as traduções são strings, você pode usar uma mensagem legível pelo usuário como uma chave (para um idioma específico).

Por exemplo:

const messages = {
+  pt: {
+    'Hello, world!': 'Olá Mundo!'
+  }
+}
+

Isso pode ser útil porque você não precisa especificar uma tradução para o "Hello, world!" na localização em inglês.

Na verdade, você pode até incluir parâmetros de modelo em uma chave. Junto com formatFallbackMessages: true, isso permite pular a escrita de modelos para o seu idioma base" e as chaves são seus modelos.

const messages = {
+  pt: {
+    'Hello {name}': 'Olá {name}'
+  }
+}
+
+const i18n = new VueI18n({
+  locale: 'pt',
+  fallbackLocale: 'en',
+  formatFallbackMessages: true,
+  messages
+})
+

Template:

<p>{{ $t('Hello {name}', { name: 'John' }}) }}</p>
+<p>{{ $t('The weather today is {condition}!', { condition: 'sunny' }) }}</p>
+

O resultado será o seguinte:

<p>Olá, John</p>
+<p>The weather today is sunny!</p>
+
+ + + diff --git a/pt/guide/formatting.html b/pt/guide/formatting.html new file mode 100644 index 000000000..c0902b343 --- /dev/null +++ b/pt/guide/formatting.html @@ -0,0 +1,221 @@ + + + + + + Formatação | Vue I18n + + + + + + + + + +

# Formatação

# Formatação nomeada

Mensagens de localização:

const messages = {
+  en: {
+    message: {
+      hello: '{msg} World'
+    }
+  },
+  pt: {
+    message: {
+      hello: '{msg} Mundo'
+    }
+  }
+}
+

Template:

<p>{{ $t('message.hello', { msg: 'Olá' }) }}</p>
+

O resultado será o seguinte:

<p>Olá Mundo</p>
+

# Formatação de lista

Mensagens de localização:

const messages = {
+  en: {
+    message: {
+      hello: '{0} World'
+    }
+  },
+  pt: {
+    message: {
+      hello: '{0} Mundo'
+    }
+  }
+}
+

Template:

<p>{{ $t('message.hello', ['Olá']) }}</p>
+

O resultado será o seguinte:

<p>Olá Mundo</p>
+

A formatação de lista também aceita objetos do tipo array:

<p>{{ $t('message.hello', {'0': 'Olá'}) }}</p>
+

O resultado será o seguinte:

<p>Olá Mundo</p>
+

# Formatação HTML

Nota

⚠️ Localizar HTML arbitrário de forma dinâmica em um site é muito perigoso porque pode facilmente levar a vulnerabilidades de XSS.
Use a interpolação HTML apenas para conteúdo confiável, nunca para conteúdo personalizado.

Recomendamos usar os recursos de interpolação de componente nesses casos.

Nota

🆕 Adicionado na versão 8.11+

Você pode controlar o uso da formatação HTML.
Consulte para obter mais detalhes a opção do construtor warnHtmlInMessage e as propriedades da API.

Em alguns casos, você pode querer renderizar sua tradução como uma mensagem HTML e não como uma string estática.

const messages = {
+  en: {
+    message: {
+      hello: 'hello <br> World'
+    }
+  },
+  pt: {
+    message: {
+      hello: 'Olá <br> Mundo'
+    }
+  }
+}
+

Template:

<p v-html="$t('message.hello')"></p>
+

Resultado (em vez da mensagem pré-formatada):

<p>
+  Olá
+  <!-- <br> existe, mas é renderizado como html e não uma string -->
+  Mundo
+</p>
+

# Suporte formatação i18n Ruby on Rails

Mensagens de localização:

const messages = {
+  en: {
+    message: {
+      hello: '%{msg} World'
+    }
+  },
+  pt: {
+    message: {
+      hello: '%{msg} Mundo'
+    }
+  }
+}
+

Template:

<p>{{ $t('message.hello', { msg: 'Olá' }) }}</p>
+

O resultado será o seguinte:

<p>Olá Mundo</p>
+

# Formatação personalizada

Às vezes, você pode precisar traduzir usando uma formatação personalizada (por exemplo, sintaxe de mensagem ICU (opens new window)).

Você pode fazer isso com um formatador personalizado que implementa a Interface do formatador (opens new window).

Um exemplo do método de formatação personalizado com a sintaxe de classe ES2015:

// Implementação do formatador personalizado
+class CustomFormatter {
+  constructor(options) {
+    // ...
+  }
+
+  //
+  // interpolate
+  //
+  // @param {string} message
+  //   string de lista ou formato nomeado
+  //   p. ex.
+  //   - formato nomeado: 'Hi {name}'
+  //   - formato de lista: 'Hi {0}'
+  //
+  // @param {Object | Array} values
+  //   valores de interpolação `message`.
+  //   valores transmitidos com `$t`, `$tc` e componente funcional `i18n`.
+  //   p. ex.
+  //   - $t('hello', { name: 'Lucas' }) -> valores passados: Object `{ name: 'Lucas' }`
+  //   - $t('hello', ['Lucas']) -> valores passados: Array `['Lucas']`
+  //   - componente funcional `i18n` (interpolação no componente)
+  //     <i18n path="hello">
+  //       <p>Lucas</p>
+  //       <p>Tudo bem com você?</p>
+  //     </i18n>
+  //     -> valores passados: Array (included VNode):
+  //        `[VNode{ tag: 'p', text: 'Lucas', ...}, VNode{ tag: 'p', text: 'Tudo bem com você?', ...}]`
+  //
+  // @return {Array<any>}
+  //   valores interpolados. Eles são necessários para retornar o seguinte:
+  //   - um array de strings ao usar `$t` ou `$tc`.
+  //   - um array incluindo o objeto VNode, ao usar `i18n` em um componente funcional.
+  //
+  interpolate(message, values) {
+    // implemente a lógica de interpolação aqui
+    // ...
+
+    // retorna o array interpolado
+    return ['resolved message string']
+  }
+}
+
+// Registre com a opção `formatter`
+const i18n = new VueI18n({
+  locale: 'en-US',
+  formatter: new CustomFormatter(/* aqui as opções do construtor */),
+  messages: {
+    'en-US': {
+      // ...
+    },
+    'pt-BR': {
+      // ...
+    }
+    // ...
+  }
+})
+
+// Iniciando o aplicativo!
+new Vue({ i18n }).$mount('#app')
+

Você também pode verificar o exemplo oficial do formatador personalizado (opens new window).

+ + + diff --git a/pt/guide/hot-reload.html b/pt/guide/hot-reload.html new file mode 100644 index 000000000..8a4077708 --- /dev/null +++ b/pt/guide/hot-reload.html @@ -0,0 +1,181 @@ + + + + + + Hot reloading | Vue I18n + + + + + + + + + +

# Hot reloading

Você pode usar o recurso Hot Module Replacement (HMR) (opens new window), você pode rastrear as mudanças em arquivos de localização e recarregá-los automaticamente em seu aplicativo.

# Exemplo básico

Para um conjunto estático de localidades, você pode especificar explicitamente o recarregamento automático dessas traduções:

import Vue from "vue"
+import VueI18n from "vue-i18n"
+import en from './en'
+import pt from './pt'
+
+const messages = {
+  en,
+  pt
+}
+
+// Instância VueI18n
+const i18n = new VueI18n({
+  locale: 'en',
+  messages
+})
+
+// Iniciando aplicativo
+const app = new Vue({
+  i18n
+  // ...
+}).$mount('#app')
+
+// Atualizações automática
+if (module.hot) {
+  module.hot.accept(['./en', './pt'], function() {
+    i18n.setLocaleMessage('en', require('./en').default)
+    i18n.setLocaleMessage('pt', require('./pt').default)
+    // Ou adicione um recarregamento automático por meio da propriedade $i18n
+    // app.$i18n.setLocaleMessage('en', require('./en').default)
+    // app.$i18n.setLocaleMessage('pt', require('./pt').default)
+  })
+}
+

# Exemplo avançado

Se precisar de suporte para uma mudança no conjunto de traduções, você pode implementar o recarregamento automático para todos os locais dinamicamente usando require.context:

import Vue from "vue";
+import VueI18n from "vue-i18n";
+
+Vue.use(VueI18n);
+
+// Carregue todos os locais e lembre-se do contexto
+function loadMessages() {
+  const context = require.context("./locales", tpte, /[a-z0-9-_]+\.json$/i);
+
+  const messages = context
+    .keys()
+    .map((key) => ({ key, locale: key.match(/[a-z0-9-_]+/i)[0] }))
+    .reduce(
+      (messages, { key, locale }) => ({
+        ...messages,
+        [locale]: context(key),
+      }),
+      {}
+    );
+
+  return { context, messages };
+}
+
+const { context, messages } = loadMessages();
+
+// Instância VueI18n
+const i18n = new VueI18n({
+  locale: "en",
+  messages,
+});
+
+// Iniciando aplicativo
+const app = new Vue({
+  i18n,
+  // ...
+}).$mount('#app');
+
+// Atualizações automática
+if (module.hot) {
+  module.hot.accept(context.id, () => {
+    const { messages: newMessages } = loadMessages();
+
+    Object.keys(newMessages)
+      .filter((locale) => messages[locale] !== newMessages[locale])
+      .forEach((locale) => {
+        messages[locale] = newMessages[locale];
+        i18n.setLocaleMessage(locale, messages[locale]);
+      });
+  });
+}
+
+ + + diff --git a/pt/guide/interpolation.html b/pt/guide/interpolation.html new file mode 100644 index 000000000..f85625e8a --- /dev/null +++ b/pt/guide/interpolation.html @@ -0,0 +1,249 @@ + + + + + + Interpolação de componentes | Vue I18n + + + + + + + + + +

# Interpolação de componentes

# Exemplo básico

Suporta a versão

🆕 7.0+

Às vezes, precisamos localizar uma mensagem de um localidade incluída em uma tag ou um componente HTML.

Por exemplo:

<p>I accept xxx <a href="/term">Terms of Service Agreement</a></p>
+

Na mensagem acima, se quisermos usar $t, provavelmente tentaremos obtê-lo vinculando as seguintes mensagens de localização:

const messages = {
+  en: {
+    term1: "I Accept xxx's",
+    term2: 'Terms of Service Agreement'
+  }
+}
+

Como resultado o template terá a seguinte aparência:

<p>{{ $t('term1') }}<a href="/term">{{ $t('term2') }}</a></p>
+

O resultado será o seguinte:

<p>I accept xxx <a href="/term">Terms of Service Agreement</a></p>
+

Isso é muito complicado, e se você mover a tag <a> para a mensagem de localização, você adicionará a possibilidade de uma vulnerabilidade XSS devido ao uso de v-html="$t('term')".

Isso pode ser evitado usando o componente funcional i18n.

Por exemplo:

<div id="app">
+  <!-- ... -->
+  <i18n path="term" tag="label" for="tos">
+    <a :href="url" target="_blank">{{ $t('tos') }}</a>
+  </i18n>
+  <!-- ... -->
+</div>
+
const messages = {
+  en: {
+    tos: 'Term of Service',
+    term: 'I accept xxx {0}.'
+  },
+  pt: {
+    tos: 'Termos de serviço',
+    term: 'Eu concordo xxx {0}.'
+  }
+}
+
+const i18n = new VueI18n({
+  locale: 'pt',
+  messages
+})
+new Vue({
+  i18n,
+  data: {
+    url: '/term'
+  }
+}).$mount('#app')
+

O resultado será o seguinte:

<div id="app">
+  <!-- ... -->
+  <label for="tos">
+    Eu concordo xxx <a href="/term" target="_blank">Termos de serviço</a>.
+  </label>
+  <!-- ... -->
+</div>
+

Mais detalhes sobre o exemplo acima, veja o exemplo (opens new window)

Descendentes do componente funcional i18n interpola mensagens de localização pelo caminho do parâmetro de path.

No exemplo acima:

<a :href="url" target="_blank">{{ $t('tos') }}</a>

interpolado com o term da mensagem de localização.

No exemplo acima, a interpolação de componentes usa formatação de lista. Os descendentes do componente da função i18n são interpolados na ordem em que aparecem.

Você pode especificar o tipo do elemento raiz usando o parâmetro de entrada tag. Se nenhum parâmetro de entrada for especificado, o padrão é 'span'. Você também pode defini-lo com o valor booleano false para inserir os nós filhos diretamente sem criar um elemento raiz.

# Usando a sintaxe de slots

Suporta a versão

🆕 8.14+

É mais conveniente usar a sintaxe de slots nomeados.

Por exemplo:

<div id="app">
+  <!-- ... -->
+  <i18n path="info" tag="p">
+    <template v-slot:limit>
+      <span>{{ changeLimit }}</span>
+    </template>
+    <template v-slot:action>
+      <a :href="changeUrl">{{ $t('change') }}</a>
+    </template>
+  </i18n>
+  <!-- ... -->
+</div>
+
const messages = {
+  en: {
+    info: 'You can {action} until {limit} minutes from departure.',
+    change: 'change your flight',
+    refund: 'refund the ticket'
+  }
+}
+
+const i18n = new VueI18n({
+  locale: 'en',
+  messages
+})
+
+new Vue({
+  i18n,
+  data: {
+    changeUrl: '/change',
+    refundUrl: '/refund',
+    changeLimit: 15,
+    refundLimit: 30
+  }
+}).$mount('#app')
+

O resultado será o seguinte:

<div id="app">
+  <!-- ... -->
+  <p>
+    You can <a href="/change">change your flight</a> until
+    <span>15</span> minutes from departure.
+  </p>
+  <!-- ... -->
+</div>
+

Desde o Vue 2.6, você pode usar a seguinte sintaxe de slots nos templates:

<div id="app">
+  <!-- ... -->
+  <i18n path="info" tag="p">
+    <template #limit>
+      <span>{{ changeLimit }}</span>
+    </template>
+    <template #action>
+      <a :href="changeUrl">{{ $t('change') }}</a>
+    </template>
+  </i18n>
+  <!-- ... -->
+</div>
+

Limitação

⚠️ Os parâmetros de entrada do slot não são suportados no componente i18n.

# Usando a sintaxe de place

Atenção!

Na próxima versão principal, os parâmetros de entrada place e places serão descontinuados. Recomendamos usar a sintaxe de slot.

Suporta a versão

🆕 7.2+

Nota

⚠️ No componente i18n, o conteúdo de texto consistindo apenas em espaços em branco será omitido.

A formatação nomeada é suportada com a ajuda do atributo place.

Por exemplo:

<div id="app">
+  <!-- ... -->
+  <i18n path="info" tag="p">
+    <span place="limit">{{ changeLimit }}</span>
+    <a place="action" :href="changeUrl">{{ $t('change') }}</a>
+  </i18n>
+  <!-- ... -->
+</div>
+
const messages = {
+  en: {
+    info: 'You can {action} until {limit} minutes from departure.',
+    change: 'change your flight',
+    refund: 'refund the ticket'
+  }
+}
+
+const i18n = new VueI18n({
+  locale: 'en',
+  messages
+})
+new Vue({
+  i18n,
+  data: {
+    changeUrl: '/change',
+    refundUrl: '/refund',
+    changeLimit: 15,
+    refundLimit: 30
+  }
+}).$mount('#app')
+

O resultado será o seguinte:

<div id="app">
+  <!-- ... -->
+  <p>
+    You can <a href="/change">change your flight</a> until
+    <span>15</span> minutes from departure.
+  </p>
+  <!-- ... -->
+</div>
+

Nota

⚠️ Para usar formatação nomeada, todos os descendentes do componente i18n devem ter o atributo place definido. Caso contrário, a formatação de lista será usada.

Se você ainda precisa interpolar o conteúdo do texto usando formatação nomeada, você pode definir a propriedade places no componente i18n.

Por exemplo:

<div id="app">
+  <!-- ... -->
+  <i18n path="info" tag="p" :places="{ limit: refundLimit }">
+    <a place="action" :href="refundUrl">{{ $t('refund') }}</a>
+  </i18n>
+  <!-- ... -->
+</div>
+

O resultado será o seguinte:

<div id="app">
+  <!-- ... -->
+  <p>
+    You can <a href="/refund">refund your ticket</a> until 30 minutes from
+    departure.
+  </p>
+  <!-- ... -->
+</div>
+
+ + + diff --git a/pt/guide/lazy-loading.html b/pt/guide/lazy-loading.html new file mode 100644 index 000000000..2641cf9e8 --- /dev/null +++ b/pt/guide/lazy-loading.html @@ -0,0 +1,156 @@ + + + + + + Lazy loading traduções | Vue I18n + + + + + + + + + +

# Lazy loading traduções

Carregar todos os seus arquivos de tradução de uma vez é exagero e desnecessário.

Lazy loading (carregamento lento) ou carregamento assíncrono de arquivos de tradução é muito fácil de implementar usando o Webpack.

Suponde que temos um diretório de projeto com a seguinte estrutura:

nosso-projeto-legal
+-dist
+-src
+--routes
+--store
+--setup
+---i18n-setup.js
+--lang
+---en.js
+---it.js
+

O diretório lang contém todos os arquivos de tradução. Vários arquivos de configuração são agrupados no diretório setup, por exemplo, configurações i18n, registro de componentes globais, inicialização de plugin e muito mais.

// i18n-setup.js
+import Vue from 'vue'
+import VueI18n from 'vue-i18n'
+import messages from '@/lang/en'
+import axios from 'axios'
+
+Vue.use(VueI18n)
+
+export const i18n = new VueI18n({
+  locale: 'en', // defenindo localidade
+  fallbackLocale: 'en',
+  messages // definindo mensagens de localização
+})
+
+const loadedLanguages = ['en'] // nosso idioma padrão que é pré-carregado
+
+function setI18nLanguage(lang) {
+  i18n.locale = lang
+  axios.defaults.headers.common['Accept-Language'] = lang
+  document.querySelector('html').setAttribute('lang', lang)
+  return lang
+}
+
+export function loadLanguageAsync(lang) {
+  // Se a localização for a mesma
+  if (i18n.locale === lang) {
+    return Promise.resolve(setI18nLanguage(lang))
+  }
+
+  // Se a localização já foi carregada
+  if (loadedLanguages.includes(lang)) {
+    return Promise.resolve(setI18nLanguage(lang))
+  }
+
+  // Se a localização ainda não foi carregada
+  return import(
+    /* webpackChunkName: "lang-[request]" */ `@/i18n/messages/${lang}.js`
+  ).then(messages => {
+    i18n.setLocaleMessage(lang, messages.default)
+    loadedLanguages.push(lang)
+    return setI18nLanguage(lang)
+  })
+}
+

Em resumo, estamos criando uma nova instância VueI18n como normalmente faríamos. Então estamos criando um array loadedLanguages que irá manter o controle de nossos idiomas carregados. A seguir está função setI18nLanguage que realmente mudará a localização na instância vueI18n, axios e onde for necessário.

A função loadLanguageAsync será usada para alterar o idioma. O carregamento de novos arquivos é feito pela função import que o Webpack fornece e nos permite carregar arquivos dinamicamente, e por usar promessas podemos facilmente esperar que o carregamento termine.

Você pode aprender mais sobre a função de importações dinâmicas na documentação do Webpack (opens new window).

É muito fácil usar loadLanguageAsync. Por exemplo, no hook beforeEach do vue-router.

router.beforeEach((to, from, next) => {
+  const lang = to.params.lang
+  loadLanguageAsync(lang).then(() => next())
+})
+

Poderíamos melhorar isso verificando se lang é realmente suportado ou não e chamando reject para que possamos pegar isso no beforeEach parando a transição da rota de navegação.

+ + + diff --git a/pt/guide/locale.html b/pt/guide/locale.html new file mode 100644 index 000000000..67758a980 --- /dev/null +++ b/pt/guide/locale.html @@ -0,0 +1,130 @@ + + + + + + Alternando localização | Vue I18n + + + + + + + + + +

# Alternando localização

Normalmente a instância raiz do Vue é usada como o ponto de verdade, e todos os componentes filhos usam a propriedade locale da classeVueI18n passada por referência.

Às vezes você pode querer alternar dinamicamente os locais. Para fazer isso, você precisa alterar o valor da propriedade locale na instânciaVueI18n.

const i18n = new VueI18n({
+  locale: 'pt', // definir a localização padrão
+  ...
+})
+
+// Crie uma instância raiz do Vue
+new Vue({
+  i18n,
+  ...
+}).$mount('#app')
+
+// Mudar para uma localização diferente
+i18n.locale = 'en'
+

Cada componente contém uma instância VueI18n que se refere à propriedade $i18n, que também pode ser usada para alterar o local.

Exemplo:

<template>
+  <div class="locale-changer">
+    <select v-model="$i18n.locale">
+      <option v-for="(lang, i) in langs" :key="`Lang${i}`" :value="lang">
+        {{ lang }}
+      </option>
+    </select>
+  </div>
+</template>
+
+<script>
+  export default {
+    name: 'locale-changer',
+    data() {
+      return { langs: ['pt', 'en'] }
+    }
+  }
+</script>
+

Aviso

⚠️ As alterações de localização são ignoradas pelos componentes com a opção sync: false.

Componente vs. escopo root

⚠️ Alterarando $i18n.locale dentro do componente não altera a localização root. Se você está contando com a localização root, por exemplo, ao usar root fallback, use $root.$I18n.locale ao vez de $i18n.locale.

+ + + diff --git a/pt/guide/messages.html b/pt/guide/messages.html new file mode 100644 index 000000000..78a6c2558 --- /dev/null +++ b/pt/guide/messages.html @@ -0,0 +1,255 @@ + + + + + + Sintaxe mensagens locais | Vue I18n + + + + + + + + + +

# Sintaxe mensagens locais

# Estrutura

Sintaxe local das mensagens:

// Como definição do Flowtype, a sintaxe das mensagens de tradução é semelhante à anotação BNF
+type LocaleMessages = { [key: Locale]: LocaleMessageObject }
+type LocaleMessageObject = { [key: Path]: LocaleMessage }
+type LocaleMessageArray = LocaleMessage[]
+type MessageContext = {
+  list: (index: number) => mixed,
+  named: (key: string) => mixed,
+  linked: (key: string) => TranslateResult,
+  values: any,
+  path: string,
+  formatter: Formatter,
+  messages: LocaleMessages,
+  locale: Locale
+};
+type MessageFunction = (ctx: MessageContext) => string;
+type LocaleMessage = string | MessageFunction | LocaleMessageObject | LocaleMessageArray;
+type Locale = string
+type Path = string
+

Com base na sintaxe acima, você pode configurar a seguinte estrutura de mensagens locais:

{
+  // localização 'pt'
+  "pt": {
+    "key1": "esta é a mensagem 1", // uso comum
+    "nested": {
+      // aninhado
+      "message1": "esta é a mensagem aninhada 1"
+    },
+    "errors": [
+      // array
+      "esta é a mensagem de código de erro 0",
+      {
+        // um objeto em array
+        "internal1": "esta é uma mensagem de código de erro interno 1"
+      },
+      [
+        // array em array
+        "este é o erro de array aninhado 1"
+      ]
+    ]
+  },
+  // localização 'en'
+  "en": {
+    // ...
+  }
+}
+

Na estrutura de mensagens locais acima, você pode traduzir usando os caminhos-chave abaixo.

<div id="app">
+  <!-- uso comum -->
+  <p>{{ $t('key1') }}</p>
+  <!-- aninhado -->
+  <p>{{ $t('nested.message1') }}</p>
+  <!-- array -->
+  <p>{{ $t('errors[0]') }}</p>
+  <!-- um objeto em array -->
+  <p>{{ $t('errors[1].internal1') }}</p>
+  <!-- array em array -->
+  <p>{{ $t('errors[2][0]') }}</p>
+</div>
+

O resultado será o seguinte:

<div id="app">
+  <!-- uso comum -->
+  <p>esta é a mensagem 1</p>
+  <!-- aninhado -->
+  <p>esta é a mensagem aninhada 1</p>
+  <!-- array -->
+  <p>esta é a mensagem de código de erro 0</p>
+  <!-- um objeto em array -->
+  <p>esta é uma mensagem de código de erro interno 1</p>
+  <!-- array em array -->
+  <p>este é o erro de array aninhado 1</p>
+</div>
+

# Mensagens de localização relacionadas

Se houver uma chave de tradução que sempre terá o mesmo texto concreto igual outra, você pode simplesmente criar um link para essa. Para vincular a outra chave de tradução, tudo que você precisa fazer é prefixar seu conteúdo com um sinal @: seguido pelo nome completo da chave de tradução incluindo o namespace ao qual deseja vincular.

Mensagens de localização a seguir:

const messages = {
+  en: {
+    message: {
+      the_world: 'the world',
+      dio: 'DIO:',
+      linked: '@:message.dio @:message.the_world !!!!'
+    }
+  }
+}
+

Template:

<p>{{ $t('message.linked') }}</p>
+

O resultado será o seguinte:

<p>DIO: the world !!!!</p>
+

# Formatando mensagens de localização relacionadas

Se o idioma distinguir casos de caracteres, você pode precisar controlar o caso das mensagens de localização relacionadas. +Mensagens relacionadas podem ser formatadas com o modificador @.modifier:key

Mensagens de localização a seguir:

  • upper: Letras maiúsculas em todos os caracteres na mensagem vinculada.
  • lower: Letras minúsculas em todos os caracteres na mensagem vinculada.
  • capitalize: Primeiro caractere em maiúsculo da mensagem vinculada.

Mensagens de localização:

const messages = {
+  en: {
+    message: {
+      homeAddress: 'Home address',
+      missingHomeAddress: 'Please provide @.lower:message.homeAddress'
+    }
+  },
+  pt: {
+    message: {
+      homeAddress: 'Endereço residencial',
+      missingHomeAddress: 'Por favor, providencie o @.lower:message.homeAddress'
+    }
+  }
+}
+
<label>{{ $t('message.homeAddress') }}</label>
+
+<p class="error">{{ $t('message.missingHomeAddress') }}</p>
+

O resultado será o seguinte:

<label>Endereço residencial</label>
+
+<p class="error">Por favor, providencie o Endereço residencial</p>
+

Você pode adicionar modificadores ou sobrescrever os existentes passando as opções de modificadores para o construtor VueI18n.

const i18n = new VueI18n({
+  locale: 'pt',
+  modifiers: {
+    // Adicionando um novo modificador
+    snakeCase: str => str.split(' ').join('-')
+  },
+  messages: {
+    // ...
+  },
+})
+

# Agrupando com parêntese

Uma chave de tradução de uma mensagem também pode ser especificada com @:(message.foo.bar.baz), onde a referência a outra chave de tradução está entre parêntese ().

Isso pode ser necessário se um ponto . for exigido após um link para outra mensagem @:message.something, que de outra forma seria considerado parte do link.

Mensagens de localização:

const messages = {
+  en: {
+    message: {
+      dio: 'DIO',
+      linked: "There's a reason, you lost, @:(message.dio)."
+    }
+  },
+  pt: {
+    message: {
+      dio: 'DIO',
+      linked: "Há uma razão pela qual você falhou, @:(message.dio)."
+    }
+  }
+}
+

Template:

<p>{{ $t('message.linked') }}</p>
+

O resultado será o seguinte:

<p>Há uma razão pela qual você falhou, DIO.</p>
+

# Mensagem com função

vue-i18n recomenda o uso de strings para formatação de lista ou formatação nomeada como mensagem de localização ao traduzir as mensagens.

No entanto, existem situações em que, devido à sintaxe complexa da linguagem, todo o poder do JavaScript é necessário. Nesse caso, em vez de mensagens de string, você pode usar uma mensagem com função.

A função abaixo retorna uma saudação:

const messages = {
+  en: {
+    greeting: (ctx) => 'Hello!'
+  },
+  pt: {
+    greeting: (ctx) => 'Olá!'
+  }
+}
+

Usar a função da mensagem é fácil! Você só precisa especificar a chave usando $t ou t:

<p>{{ $t('greeting') }}</p>
+

O resultado será o seguinte:

<p>Olá!</p>
+

O resultado de retorno da função é usado para a mensagem.

# Formatação nomeada

vue-i18n suporta formatação nomeada como um formato de mensagem baseado em string. vue-i18n interpola os valores dos parâmetros com $t ou t, e os retorna.

O mesmo pode ser feito com a função da mensagem usando o contexto de mensagem:

Aqui está o exemplo de saudação:

const messages = {
+  en: {
+    greeting: (ctx) => `Hello, ${ctx.named('name')}!`
+  },
+  pt: {
+    greeting: (ctx) => `Olá, ${ctx.named('name')}!`
+  }
+}
+

Template:

<p>{{ $t('greeting', { name: 'DIO' }) }}</p>
+

O resultado será o seguinte:

<p>Olá, DIO!</p>
+

O contexto da mensagem fornece acesso à função named. Você deve especificar a chave especificada para $t ou t, que resolverá com o valor necessário.

# Formatação de lista

O uso da formatação de lista é semelhante ao formatação nomeada descrito acima.

vue-i18n suporta formatação de lista para mensagens de string. vue-i18n interpola os valores dos parâmetros com $t ou t, e os retorna.

O mesmo pode ser feito com a função da mensagem usando o contexto de mensagem:

Aqui está o exemplo de saudação:

const messages = {
+  en: {
+    greeting: (ctx) => `Hello, ${ctx.list(0)}!`
+  },
+  pt: {
+    greeting: (ctx) => `Olá, ${ctx.list(0)}!`
+  }
+}
+

Template:

<p>{{ $t('greeting', ['DIO']) }}</p>
+

O resultado será o seguinte:

<p>Olá, DIO!</p>
+

O contexto da mensagem fornece acesso à função list. Você deve especificar a chave especificada para $t ou t, que resolverá com o valor necessário.

# Limitação

Em uma função para mensagem, os seguintes recursos, que estão disponíveis em uma versão de string, não estarão disponíveis por meio do contexto da mensagem:

  • Mensagens de localidade vinculadas
  • Pluralização
+ + + diff --git a/pt/guide/number.html b/pt/guide/number.html new file mode 100644 index 000000000..440e6f037 --- /dev/null +++ b/pt/guide/number.html @@ -0,0 +1,166 @@ + + + + + + Localização de números | Vue I18n + + + + + + + + + +

# Localização de números

Suporta a versão

🆕 7.0+

Você pode localizar números com seus formatos de definição.

Formato de exemplo para números:

const numberFormats = {
+  'en-US': {
+    currency: {
+      style: 'currency',
+      currency: 'USD'
+    }
+  },
+  'pt-BR': {
+    currency: {
+      style: 'currency',
+      currency: 'BRL',
+      currencyDisplay: 'symbol'
+    }
+  }
+}
+

Conforme declarado acima, você pode especificar formatos numéricos (por exemplo, currency para moeda) usando opções ECMA-402 Intl.NumberFormat (opens new window).

Depois disso, para poder usar este formato em mensagens de localização, você precisa definir a opção numberFormats do construtor na instância VueI18n:

const i18n = new VueI18n({
+  numberFormats
+})
+
+new Vue({
+  i18n
+}).$mount('#app')
+

Template:

<div id="app">
+  <p>{{ $n(100, 'currency') }}</p>
+  <p>{{ $n(100, 'currency', 'pt-BR') }}</p>
+</div>
+

O resultado será o seguinte:

<div id="app">
+  <p>$100.00</p>
+  <p>100,00 ₽</p>
+</div>
+

# Formatação personalizada

Suporta a versão

🆕 8.10+

O método $n retorna o resultado como uma string numérica totalmente formatada que só pode ser usada em sua totalidade. Nos casos em que você precisa estilizar alguma parte de um número formatado (por exemplo, uma parte fracionária), $n não será suficiente. Nesses casos, é necessário usar o componente funcional <i18n-n> será útil.

Com um conjunto mínimo de propriedades, <i18n-n> gera o mesmo resultado que $n envolvido em um elemento DOM configurado.

Template:

<div id="app">
+  <i18n-n :value="100"></i18n-n>
+  <i18n-n :value="100" format="currency"></i18n-n>
+  <i18n-n :value="100" format="currency" locale="pt-BR"></i18n-n>
+</div>
+

O resultado será o seguinte:

<div id="app">
+  <span>100</span>
+  <span>$100.00</span>
+  <span>R$ 100,00</span>
+</div>
+

O verdadeiro poder deste componente entra em ação quando é usado com slots com escopo (opens new window).

Digamos que haja um requisito para exibir a parte inteira de um número em negrito. Isso pode ser obtido especificando integer no elemento do slot com escopo:

<i18n-n :value="100" format="currency">
+  <span v-slot:integer="slotProps" styles="font-weight: bold">
+    {{ slotProps.integer }}
+  </span>
+</i18n-n>
+

O resultado será o seguinte:

<span>$<span styles="font-weight: bold">100</span>.00</span>
+

É possível especificar vários slots com escopo ao mesmo tempo:

<i18n-n :value="1234" :format="{ key: 'currency', currency: 'EUR' }">
+  <span v-slot:currency="slotProps" styles="color: green">
+    {{ slotProps.currency }}
+  </span>
+  <span v-slot:integer="slotProps" styles="font-weight: bold">
+    {{ slotProps.integer }}
+  </span>
+  <span v-slot:group="slotProps" styles="font-weight: bold">
+    {{ slotProps.group }}
+  </span>
+  <span v-slot:fraction="slotProps" styles="font-size: small">
+    {{ slotProps.fraction }}
+  </span>
+</i18n-n>
+

(O HTML de resultado abaixo é formatado para melhor legibilidade)

<span>
+  <span styles="color: green"></span>
+  <span styles="font-weight: bold">1</span>
+  <span styles="font-weight: bold">,</span>
+  <span styles="font-weight: bold">234</span>
+  <span styles="font-size: small">00</span>
+</span>
+

Você pode especificar o tipo do elemento raiz usando o parâmetro de entrada tag. Se nenhum parâmetro de entrada for especificado, o padrão é 'span'. Você também pode defini-lo com o valor booleano false para inserir os nós filhos diretamente sem criar um elemento raiz.

A lista completa dos slots de escopo suportados, bem como outras propriedades <i18n-n>, pode ser encontradas na página da API.

+ + + diff --git a/pt/guide/pluralization.html b/pt/guide/pluralization.html new file mode 100644 index 000000000..ecccecafd --- /dev/null +++ b/pt/guide/pluralization.html @@ -0,0 +1,203 @@ + + + + + + Pluralização | Vue I18n + + + + + + + + + +

# Pluralização

Você pode usar pluralização para mensagens traduzidas. Para fazer isso, precisa definir a localidade e especificar as strings de tradução para os diferentes casos por meio do separador |.

Seu template precisará usar $tc() em vez de $t().

Mensagens locais abaixo:

const messages = {
+  en: {
+    car: 'car | cars',
+    apple: 'no apples | one apple | {count} apples'
+  },
+  pt: {
+    car: 'carro | carros',
+    apple: 'sem maçãs | uma maçã | {count} maçãs'
+  }
+}
+

Template:

<p>{{ $tc('car', 1) }}</p>
+<p>{{ $tc('car', 2) }}</p>
+
+<p>{{ $tc('apple', 0) }}</p>
+<p>{{ $tc('apple', 1) }}</p>
+<p>{{ $tc('apple', 10, { count: 10 }) }}</p>
+

O resultado será o seguinte:

<p>carro</p>
+<p>carros</p>
+
+<p>sem maçãs</p>
+<p>uma maçã</p>
+<p>10 maçãs</p>
+

# Acessando o número por meio do argumento predefinido

Não há necessidade de passar explicitamente o número para pluralização. Em mensagens de localização, um número está disponível através dos argumentos nomeados {count} e/ou {n}. Você pode substituí-los, se desejar.

Mensagens locais abaixo:

const messages = {
+  en: {
+    apple: 'no apples | one apple | {count} apples',
+    banana: 'no bananas | {n} banana | {n} bananas'
+  },
+  pt: {
+    apple: 'sem maçãs | uma maçã | {count} maçãs'
+    banana: 'sem bananas | {n} banana | {n} bananas'
+  }
+}
+

Template:

<p>{{ $tc('apple', 10, { count: 10 }) }}</p>
+<p>{{ $tc('apple', 10) }}</p>
+
+<p>{{ $tc('banana', 1, { n: 1 }) }}</p>
+<p>{{ $tc('banana', 1) }}</p>
+<p>{{ $tc('banana', 100, { n: 'Muitas' }) }}</p>
+

O resultado será o seguinte:

<p>10 maçãs</p>
+<p>10 maçãs</p>
+
+<p>1 banana</p>
+<p>1 banana</p>
+<p>Muitas bananas</p>
+

# Pluralização personalizadas

Essa pluralização, entretanto, não se aplica a todas as línguas (as línguas eslavas, por exemplo, têm regras de pluralização diferentes).

Para implementar essas regras, você pode passar um objeto pluralizationRules opcional para as opções do construtor VueI18n.

Um exemplo simplificado para idiomas eslavos (russo, ucraniano e outros):

new VueI18n({
+  // Key - idioma para usar a regra, `'ru'`, neste caso
+  // Value - função para escolher a forma plural correta
+  pluralizationRules: {
+    /**
+     * @param choice {number} um índice de escolha dado pela entrada de $tc: `$tc('path.to.rule', choiceIndex)`
+     * @param choicesLength {number} quantidade geral de opções disponíveis
+     * @returns índice final para selecionar as palavras no plural
+     */
+    'ru': function(choice, choicesLength) {
+      // this === Instância VueI18n, então a propriedade locale também existe aqui
+
+      if (choice === 0) {
+        return 0;
+      }
+
+      const teen = choice > 10 && choice < 20;
+      const endsWithOne = choice % 10 === 1;
+
+      if (choicesLength < 4) {
+        return (!teen && endsWithOne) ? 1 : 2;
+      }
+      if (!teen && endsWithOne) {
+        return 1;
+      }
+      if (!teen && choice % 10 >= 2 && choice % 10 <= 4) {
+        return 2;
+      }
+
+      return (choicesLength < 4) ? 2 : 3;
+    }
+  }
+})
+

Essa implementação permitirá que você use:

const messages = {
+  ru: {
+    car: '0 машин | {n} машина | {n} машины | {n} машин',
+    banana: 'нет бананов | {n} банан | {n} банана | {n} бананов'
+  }
+}
+

Onde o formato é 0 coisas | número de itens termina em 1 | o número de coisas que termina em 2-4 | o número de coisas que termina com 5-9, 0 e o número coisas que termina de 11 a 19. +P.S. A pluralização eslava é complexa, você pode ler mais sobre isso aqui (opens new window).

No template, você ainda precisa usar $tc() em vez de $t():

<p>{{ $tc('car', 1) }}</p>
+<p>{{ $tc('car', 2) }}</p>
+<p>{{ $tc('car', 4) }}</p>
+<p>{{ $tc('car', 12) }}</p>
+<p>{{ $tc('car', 21) }}</p>
+
+<p>{{ $tc('banana', 0) }}</p>
+<p>{{ $tc('banana', 4) }}</p>
+<p>{{ $tc('banana', 11) }}</p>
+<p>{{ $tc('banana', 31) }}</p>
+

O resultado será o seguinte:

<p>1 машина</p>
+<p>2 машины</p>
+<p>4 машины</p>
+<p>12 машин</p>
+<p>21 машина</p>
+
+<p>нет бананов</p>
+<p>4 банана</p>
+<p>11 бананов</p>
+<p>31 банан</p>
+

# Pluralização padrão

Se nenhuma regra de pluralização for fornecida para a localidade em uso, a regra padrão do idioma inglês será usada.

+ + + diff --git a/pt/guide/sfc.html b/pt/guide/sfc.html new file mode 100644 index 000000000..36f90ab8a --- /dev/null +++ b/pt/guide/sfc.html @@ -0,0 +1,387 @@ + + + + + + Componentes de arquivo único | Vue I18n + + + + + + + + + +

# Componentes de arquivo único

# Uso básico

Se você estiver construindo um componente ou aplicativo Vue usando componentes de arquivo único, você pode gerenciar as mensagens de localização usando um bloco i18n personalizado.

Código de componente com exemplo de componentes de arquivo único (opens new window):

<i18n>
+{
+  "en": {
+    "hello": "Hello World!"
+  },
+  "pt": {
+    "hello": "Olá Mundo!"
+  }
+}
+</i18n>
+
+<template>
+  <div id="app">
+    <label for="locale">Idiomas</label>
+    <select v-model="locale">
+      <option>en</option>
+      <option>pt</option>
+    </select>
+    <p>Mensagem: {{ $t('hello') }}</p>
+  </div>
+</template>
+
+<script>
+export default {
+  name: 'app',
+  data () {
+    this.$i18n.locale = 'pt';
+    return { locale: 'pt' }
+  },
+  watch: {
+    locale (val) {
+      this.$i18n.locale = val
+    }
+  }
+}
+</script>
+

# Instalação vue-i18n-loader

Você precisa instalar vue-loader e vue-i18n-loader devido ao uso de blocos personalizados <i18n>. Embora vue-loader (opens new window) provavelmente já seja usado em seu projeto se você estiver trabalhando com componentes de arquivo único, mas você vai precisar instalar vue-i18n-loader (opens new window) adicionalmente:

npm i --save-dev @kazupon/vue-i18n-loader
+

# Webpack

O Webpack requer a seguinte configuração:

Para vue-loader v15 ou posterior:

module.exports = {
+  // ...
+  module: {
+    rules: [
+      {
+        test: /\.vue$/,
+        loader: 'vue-loader'
+      },
+      {
+        resourceQuery: /blockType=i18n/,
+        type: 'javascript/auto',
+        loader: '@kazupon/vue-i18n-loader'
+      }
+      // ...
+    ]
+  }
+  // ...
+}
+

Para vue-loader v14:

module.exports = {
+  // ...
+  module: {
+    rules: [
+      {
+        test: /\.vue$/,
+        loader: 'vue-loader',
+        options: {
+          loaders: {
+            // você precisa especificar a chave do carregador `i18n` com o `vue-i18n-loader`
+            // (https://github.com/kazupon/vue-i18n-loader)
+            i18n: '@kazupon/vue-i18n-loader'
+          }
+        }
+      }
+      // ...
+    ]
+  }
+  // ...
+}
+

# Vue CLI 3.0

Vue CLI 3.0 (opens new window) ocultar a configuração do Webpack, portanto, para adicionar suporte para tags <i18n> em componentes de arquivo único, precisamos modificar a configuração existente.

Para fazer isso, temos que criar um vue.config.js na raiz do nosso projeto. Depois de fazer isso, devemos incluir o seguinte código:

Para vue-loader v15 ou posterior:

module.exports = {
+  chainWebpack: config => {
+    config.module
+      .rule('i18n')
+      .resourceQuery(/blockType=i18n/)
+      .type('javascript/auto')
+      .use('i18n')
+        .loader('@kazupon/vue-i18n-loader')
+        .end()
+  }
+}
+

Para vue-loader v14:

const merge = require('deepmerge')
+
+module.exports = {
+  chainWebpack: config => {
+    config.module
+      .rule('vue')
+      .use('vue-loader')
+      .tap(options =>
+        merge(options, {
+          loaders: {
+            i18n: '@kazupon/vue-i18n-loader'
+          }
+        })
+      )
+  }
+}
+

Não se esqueça de instalar o deepmerge (opens new window)! (npm i deepmerge -D ou yarn add deepmerge -D)

Você pode aprender mais sobre as possibilidades de modificar a configuração do Webpack existente neste guia (opens new window).

# Laravel-Mix

Para Laravel-mix 4 com vue-loader v15 ou posterior:

// Estenda o Mix usando o método "i18n", que carrega o vue-i18n-loader
+mix.extend( 'i18n', new class {
+        webpackRules() {
+            return [
+                {
+                    resourceQuery: /blockType=i18n/,
+                    type:          'javascript/auto',
+                    loader:        '@kazupon/vue-i18n-loader',
+                },
+            ];
+        }
+    }(),
+);
+
+// Certifique-se de chamar .i18n() para carregar o loader antes do .js(..., ...)
+mix.i18n()
+   .js( 'resources/js/App.js', 'public/js/app.js' )
+   ...
+

para Laravel-mix 2 com vue-loader v14:

No Laravel-mix, começando na versão V2.1 (opens new window), você pode adicionar regras personalizadas usando mix.extend(). O Laravel-mix já possui suas próprias regras para lidar com arquivos .vue. Para adicionar vue-i18n-loader, no arquivo webpack.mix.js adicione o seguinte código:

// O código a seguir injetará o i18n Kazupon/vue-18-loader como o loader de arquivos .vue
+mix.extend( 'i18n', function( webpackConfig, ...args ) {
+    webpackConfig.module.rules.forEach( ( module ) => {
+        // Procure o componente "vue-loader", que processa os arquivos .vue
+        if( module.loader !== 'vue-loader' ) {
+            return;
+        }
+
+        // Neste módulo, adicione o vue-i18n-loader para a tag i18n.
+        module.options.loaders.i18n = '@kazupon/vue-i18n-loader';
+    } );
+} );
+
+// Certifique-se de chamar .i18n() para carregar o loader antes de .js(..., ...)
+mix.i18n()
+   .js( 'resources/assets/js/App.js', 'public/js/app.js' )
+   ...
+

# Carregando YAML

Os blocos personalizados i18n podem ser especificados no formato JSON ou YAML usando o recurso de pré-carregador do vue-loader.

Os blocos personalizados i18n no formato YAML:

<i18n>
+  en:
+    hello: "Hello World!"
+  pt:
+    hello: "Olá Mundo!"
+</i18n>
+

Configuração do Webpack:

Para vue-loader v15 ou posterior:

// Vue CLI 3.0
+module.exports = {
+  chainWebpack: config => {
+    config.module
+      .rule('i18n')
+      .resourceQuery(/blockType=i18n/)
+      .type('javascript/auto')
+      .use('i18n')
+        .loader('@kazupon/vue-i18n-loader')
+        .end()
+      .use('yaml')
+        .loader('yaml-loader')
+        .end()
+  }
+}
+

Para vue-loader v14:

module.exports = {
+  // ...
+  module: {
+    rules: [
+      {
+        test: /\.vue$/,
+        loader: 'vue-loader',
+        options: {
+          preLoaders: {
+            i18n: 'yaml-loader'
+          },
+          loaders: {
+            i18n: '@kazupon/vue-i18n-loader'
+          }
+        }
+      }
+      // ...
+    ]
+  }
+  // ...
+}
+

# Vários blocos personalizados

Você pode usar mensagens de localização com vários blocos personalizados i18n.

<i18n src="./common/locales.json"></i18n>
+<i18n>
+  {
+    "en": {
+      "hello": "Hello World!"
+    },
+    "pt": {
+      "hello": "Olá Mundo!"
+    }
+  }
+</i18n>
+

No exemplo acima, o primeiro bloco personalizado carrega as mensagens de localização genérica usando o atributo src, o segundo bloco personalizado carrega as mensagens de localização que são definidas apenas neste componente de arquivo único. Todos eles serão mesclados com mensagens de localização de componentes.

Desta forma, vários blocos personalizados são úteis quando usados ​​como módulos.

# Estilos Locais

Ao usar vue-i18n com estilos locais style scoped, é importante lembrar de usar deep selector (opens new window) para estilizar o elemento dentro da string de tradução.

Por exemplo:

Quando a tradução contém apenas texto (funciona sem deep selector)

<i18n>
+  {
+    "en": {
+      "hello": "Hello World!"
+    },
+    "pt": {
+      "hello": "Olá Mundo!"
+    }
+  }
+</i18n>
+
+<template>
+  <div class="parent">
+    <p>Mensagem: {{ $t('hello') }}</p>
+  </div>
+</template>
+
+<!-- Vai funcionar por exemplo -->
+<style scoped>
+  .parent p {
+    color: #42b883;
+  }
+</style>
+

Tradução que contém elemento HTML (deve usar deep selector)

<i18n>
+  {
+    "en": {
+      "hello": "Hello <span>World!</span>"
+    },
+    "pt": {
+      "hello": "Olá <span>Mundo!</span>"
+    }
+  }
+</i18n>
+
+<template>
+  <div class="parent">
+    <p v-html="$t('hello')"></p>
+  </div>
+</template>
+
+<!-- Não vai funcionar por exemplo -->
+<style scoped>
+  .parent p {
+    color: #42b883;
+  }
+
+  .parent p span {
+    color: red;
+  }
+</style>
+
+<!-- Vai funcionar por exemplo >>> -->
+<style scoped>
+  .parent p {
+    color: #42b883;
+  }
+
+  .parent p >>> span {
+    color: red;
+  }
+</style>
+
+<!-- Vai funcionar por exemplo /deep/ -->
+<style scoped>
+  .parent p {
+    color: #42b883;
+  }
+
+  .parent p /deep/ span {
+    color: red;
+  }
+</style>
+
+<!-- Vai funcionar por exemplo ::v-deep -->
+<style scoped>
+  .parent p {
+    color: #42b883;
+  }
+
+  ::v-deep .parent p span {
+    color: red;
+  }
+</style>
+

# Blocos personalizados em componente funcional

Se os componentes de arquivo único têm o template usando um componente funcional, e você definiu blocos personalizados i18n, observe que você não pode localizar usando mensagens de local.

Por exemplo, o código a seguir não pode usar mensagens de localização do bloco i18n.

<i18n>
+  {
+    "en": {
+      "hello": "Hello World"
+    },
+    "pt": {
+      "hello": "Olá Mundo"
+    }
+  }
+</i18n>
+
+<template functional>
+  <!-- Mensagem de localização 'hello' na instância pai -->
+  <p>{{ parent.$t('hello') }}</p>
+</template>
+
+ + + diff --git a/pt/guide/tooling.html b/pt/guide/tooling.html new file mode 100644 index 000000000..f13a551fb --- /dev/null +++ b/pt/guide/tooling.html @@ -0,0 +1,95 @@ + + + + + + Ferramentas | Vue I18n + + + + + + + + + +

# Ferramentas

Para suportar os aplicativos i18n do Vue, algumas ferramentas são fornecidas oficialmente.

Existem também ferramentas de terceiros que integram o Vue I18n.

# Ferramentas oficiais

# Plugin para Vue CLI

vue-cli-plugin-i18n (opens new window) é o plugin oficial para o Vue CLI.

Com este plugin, você pode configurar um ambiente i18n para seu aplicativo Vue e oferecer suporte ao ambiente de desenvolvimento i18n.

# Módulo para Nuxt

nuxt-i18n (opens new window) é o módulo correspondente para Nuxt.js.

# Loader para Webpack

vue-i18n-loader (opens new window) — é o loader para webpack oficial.

Com este loader é possível usar blocos i18n personalizados em componentes de arquivo único.

Para obter mais informações sobre blocos i18n personalizados, consulte Componentes de arquivo único

# Plugin para ESLint

eslint-plugin-vue-i18n (opens new window) - Plug-in ESLint para Vue I18n.

Permite que você integre facilmente alguns recursos de localização do lint ao seu aplicativo Vue.js.

# Extensões

vue-i18n-extensions (opens new window) fornece algumas extensões para Vue I18n.

Você pode usar esta extensão para habilitar o SSR e melhorar o desempenho do i18n.

# Ferramentas de terceiros

# BabelEdit

BabelEdit (opens new window) é um editor de tradução para aplicativos da web.

O BabelEdit pode traduzir arquivos json e também pode trabalhar com blocos personalizados i18n de componentes de arquivo único.

Mais informações sobre o BabelEdit podem ser encontradas na página de introdução (opens new window).

# i18n Ally

[i18n Ally] (https://marketplace.visualstudio.com/items?itemName=antfu.i18n-ally) é uma extensão i18n para VSCode.

i18n Ally oferece um DX(Experiência do desenvolvedor) incrível para o desenvolvimento de i18n.

Você pode aprender mais sobre a extensão i18n Ally em README (opens new window).

# i18nPlugin (plataforma intellij)

i18nPlugin (opens new window) — Plugin de suporte para idea Intellij i18next (Página do plugin Jetbrains (opens new window)).

Plugin para i18n typescript/javascript/PHP. Suporta vue-i18n. Para habilitar o suporte a vue-i18n vá em configurações -> Ferramentas -> Configuração do plugin i18n e selecione "Vue-i18n". É necessário instalar os diretórios com os arquivos de tradução (tradução por padrão).

# vue-i18n-extract

vue-i18n-extract (opens new window) faz uma análise estática de um projeto Vue.js com base em vue-i18n e relata as seguintes informações:

  • lista de todas as chaves vue-i18n não utilizadas (entradas encontradas nos arquivos de idioma, mas não utilizadas no projeto)
  • lista de todas as chaves ausentes (entradas encontradas no projeto, mas não nos arquivos de idioma)

É possível mostrar a saída no console ou gravá-la em um arquivo json.

As chaves ausentes também podem ser adicionadas automaticamente aos arquivos de tradução fornecidos.

+ + + diff --git a/pt/index.html b/pt/index.html new file mode 100644 index 000000000..9ceaeb350 --- /dev/null +++ b/pt/index.html @@ -0,0 +1,101 @@ + + + + + + Vue I18n + + + + + + + + + +
hero

+ Vue I18n +

+ Vue I18n é um internacionalizador de idiomas para Vue.js +

+ Introdução → +

🥇 Patrocinadores Ouro

Nuxt.js

🥈 Patrocinadores prata

Editor de tradução BabelEdit para aplicativos (web apps)

🥉 Patrocinadores Bronze

zenarchitects sendcloud

Simples

Você pode introduzir a internacionalização em seu aplicativo com uma API simples.

Poderoso

Além de traduções simples, suporta a localização, com pluralização, número, data, hora... e etc.

Orientado a componentes

Você pode gerenciar as mensagens de localização dentro de componentes de arquivo único.

+ + + diff --git a/pt/installation.html b/pt/installation.html new file mode 100644 index 000000000..2047adcdb --- /dev/null +++ b/pt/installation.html @@ -0,0 +1,114 @@ + + + + + + Instalação | Vue I18n + + + + + + + + + +

# Instalação

# Nota de compatibilidade

  • Vue.js versões 2.0.0+

# Download direto / CDN

https://unpkg.com/vue-i18n/dist/vue-i18n (opens new window)

O serviço unpkg.com (opens new window) fornece links CDN com base em pacotes NPM. O link acima sempre apontará para a versão mais recente do NPM. Você pode usar uma versão ou tag específica usando um URL como este https://unpkg.com/vue-i18n@8.17.5/dist/vue-i18n.js (opens new window)

Ao conectar o vue-i18n após o Vue, o plug-in será instalado automaticamente:

<script src="https://unpkg.com/vue/dist/vue.js"></script>
+<script src="https://unpkg.com/vue-i18n/dist/vue-i18n.js"></script>
+

# NPM

npm install vue-i18n
+

# Yarn

yarn add vue-i18n
+

Ao usar o sistema de módulos, você deve definir explicitamente vue-i18n +via Vue.use():

import Vue from 'vue'
+import VueI18n from 'vue-i18n'
+
+Vue.use(VueI18n)
+

Você não precisa fazer isso ao usar tags de script globais <script>.

# Vue CLI 3.x

vue add i18n
+

O Vue CLI 3.x deve ser instalado previamente, podendo instalá-lo com o próximo comando:

npm install @vue/cli -g
+

# Dev Build

Se você precisa utilizar a última compilação de dev, precisará clonar o repositório do GitHub e compilar vue-i18n você mesmo.

git clone https://github.com/kazupon/vue-i18n.git node_modules/vue-i18n
+cd node_modules/vue-i18n
+npm install # ou `yarn`
+npm run build  # ou `yarn run build`
+

# Explicação sobre diferentes versões

Dentro do diretório dist/ do pacote NPM (opens new window) você encontrará muitas compilações diferentes do VueI18n. Aqui está uma visão geral da diferença entre eles:

  • UMD: vue-i18n.js
  • CommonJS: vue-i18n.common.js
  • ES Module para empacotadores: vue-i18n.esm.js
  • ES Module para navegadores: vue-i18n.esm.browser.js

# Termos

  • UMD (opens new window): As compilações UMD podem ser usadas diretamente no navegador através de uma tag <script>. O arquivo padrão do Unpkg CDN em https://unpkg.com/vue-i18n (opens new window) é a versão UMD compilada (vue-i18n.js).

  • CommonJS (opens new window): As compilações do CommonJS são destinadas ao uso com sistemas de compilação mais antigos, como browserify (opens new window) ou webpack 1 (opens new window). O arquivo padrão para esses sistemas de compilação (pkg.main) é a compilação CommonJS (vue-i18n.common.js).

  • ES Module (opens new window): VueI18n desde a versão 8.11 fornece duas compilações de Módulos ES (ESM):

    • ESM para sistemas de compilação: projetado para uso com sistemas de compilação modernos, como webpack 2 (opens new window) ou Rollup (opens new window). O formato ESM é projetado para análise estática para que os sistemas de construção possam realizar uma "agitação de árvore" e remover o código não utilizado no pacote final. O arquivo padrão para esses sistemas de construção (pkg.module) é a construção do Módulo ES somente em tempo de execução (vue-i18n.esm.js).
    • ESM para navegadores (apenas para 8.11+, vue-i18n.esm.browser.js): destinado a importações diretas em navegadores modernos usando a tag <script type="module">.
+ + + diff --git a/pt/introduction.html b/pt/introduction.html new file mode 100644 index 000000000..86a65fb4f --- /dev/null +++ b/pt/introduction.html @@ -0,0 +1,97 @@ + + + + + + Introdução | Vue I18n + + + + + + + + + +

# Introdução

Atenção

⚠️ Documentação para Vue I18n v6.0 ou posterior. Se você estiver usando e procurando por documentação para v5.x, consulte Legado.

Vue I18n é um plugin para internacionalização em Vue.js. Ele integra facilmente recursos de localização ao seu aplicativo Vue.js.

É melhor começar o estudo pela a seção Iniciando

# Patrocinadores

# 🥇 Ouro

Nuxt.js

# 🥈 Prata

Editor de tradução BabelEdit para aplicativos (web)

# 🥉 Bronze

zenarchitects sendcloud

# Ajude no Patreon

Sua empresa usa vue-i18n ou vue-cli-plugin-i18n para criar aplicativos incríveis? Junte-se a outros patrocinadores ou torne-se um patrocinador para ver seu logotipo na documentação! +O suporte do Patreon permite ao autor que trabalhe menos e desenvolva mais em software de código aberto como o vue-i18n! +Obrigado!

+ + + diff --git a/pt/started.html b/pt/started.html new file mode 100644 index 000000000..64645077b --- /dev/null +++ b/pt/started.html @@ -0,0 +1,141 @@ + + + + + + Iniciando | Vue I18n + + + + + + + + + +

# Iniciando

NOTA

Neste guia usamos ES2015 (opens new window) nos exemplos de código.

# HTML

<script src="https://unpkg.com/vue/dist/vue.js"></script>
+<script src="https://unpkg.com/vue-i18n/dist/vue-i18n.js"></script>
+
+<div id="app">
+  <p>{{ $t("message.hello") }}</p>
+</div>
+

# JavaScript

// Se você usa um sistema de módulos (p. ex. via vue-cli)
+// Importe o Vue e VueI18n assim utilize-o Vue.use(VueI18n).
+//
+// import Vue from 'vue'
+// import VueI18n from 'vue-i18n'
+//
+// Vue.use(VueI18n)
+
+// Mensagens traduzidas de suas localidades
+const messages = {
+  en: {
+    message: {
+      hello: 'Hello World'
+    }
+  },
+  pt: {
+    message: {
+      hello: 'Olá Mundo'
+    }
+  }
+}
+
+// Crie uma instância do VueI18n com opções
+const i18n = new VueI18n({
+  locale: 'pt', // Defina uma localidade
+  messages, // Defina as mensagens
+})
+
+
+// Crie uma instância Vue com a opção `i18n`
+new Vue({ i18n }).$mount('#app')
+
+// Pronto agora o aplicativo foi iniciado!
+

O resultado será o seguinte:

<div id="#app">
+  <p>Olá Mundo</p>
+</div>
+
+ + + diff --git a/ru/api/index.html b/ru/api/index.html new file mode 100644 index 000000000..6f482cfa6 --- /dev/null +++ b/ru/api/index.html @@ -0,0 +1,177 @@ + + + + + + Справочник API | Vue I18n + + + + + + + + + +

# Справочник API

# Расширение прототипа Vue

# Опции конструктора Vue

# i18n

  • Тип: I18nOptions

Опция локализации на основе компонентов.

  • См. также: Опции конструктора класса VueI18n

# Внедряемые методы

# $t

  • Аргументы:

    • {Path} key: обязательный
    • {Locale} locale: опционально
    • {Array | Object} values: опционально
  • Возвращает: TranslateResult

Получение переведённого сообщения по ключу key. Сообщения локализации в компоненте имеют приоритет над глобальными сообщениями. Если сообщений локализации в компоненте нет, то локализация осуществляется с помощью глобальных сообщений локализации. Если указана locale, то используются сообщения локализации из locale. Если был указан key именованного формата / формата списков сообщений локализации, то необходимо указывать также values. Подробнее про значения values можно изучить в разделе Формат сообщений локализации.

Совет

Обратите внимание, что в хуках жизненного цикла контекст должен быть экземпляром компонента (например в опции data, const $t = this.$t.bind(this)).

# $tc

  • Аргументы:

    • {Path} key: обязательный
    • {number} choice: опционально, по умолчанию 1
    • {Locale} locale: опционально
    • {string | Array | Object} values: опционально
  • Возвращает: TranslateResult

Получение переведённого сообщения по ключу key с использованием плюрализации. Сообщения локализации компонента имеют приоритет над глобальными сообщениями. Если сообщений локализации в компоненте нет, то локализация осуществляется с помощью глобальных сообщений локализации. Если указана locale, то используются сообщения локализации из locale. Если указано строковое значение для values, то локализация выполняется для этого значения. Если указано значение Array или Object в values, то необходимо указывать с values из $t.

Если вам не подходит реализация плюрализации по умолчанию, смотрите pluralization rules в опциях конструктора и пользовательскую плюрализацию.

Совет

Обратите внимание, что в хуках жизненного цикла контекст должен быть экземпляром компонента (например в опции data, const $tc = this.$tc.bind(this)).

# $te

  • Аргументы:

    • {Path} key: обязательный
    • {Locale} locale: опционально
  • Возвращает: boolean

Проверяет существует ли перевод для ключа в сообщениях локализации. Если нет сообщений локализации в компоненте, то проверяет в глобальных сообщениях локализации. Если указана locale, то проверяется наличие в сообщениях локализации locale.

Совет

Обратите внимание, что в хуках жизненного цикла контекст должен быть экземпляром компонента (например в опции data, const $te = this.$te.bind(this)).

# $d

🆕 Добавлено в версии 7.0+

  • Аргументы:

    • {number | Date} value: обязательный
    • {Path | Object} key: опционально
    • {Locale | Object} locale: опционально
  • Возвращает: DateTimeFormatResult

Локализация даты из value по указанному формату даты из key. Формат указанный в key должен быть зарегистрирован в опции dateTimeFormats класса VueI18n, и зависит от опции locale конструктора VueI18n. Если указать аргумент locale, то он будет иметь приоритет над опцией locale конструктора VueI18n.

Если формата даты для key нет в опции dateTimeFormats, то будет использован запасной формат, основываясь на опции fallbackLocale конструктора VueI18n.

Совет

Обратите внимание, что в хуках жизненного цикла контекст должен быть экземпляром компонента (например в опции data, const $d = this.$d.bind(this)).

# $n

🆕 Добавлено в версии 7.0+

  • Аргументы:

    • {number} value: обязательный
    • {Path | Object} format: опционально
    • {Locale} locale: опционально
  • Возвращает: NumberFormatResult

Локализация числа value с помощью формата чисел format. Числовой формат из format должен быть зарегистрирован в опции numberFormats класса VueI18n, и зависит от опции locale конструктора VueI18n. Если указать аргумент locale, то он будет иметь приоритет над опцией locale конструктора VueI18n.

Если формат чисел для format не указан в опции numberFormats, будет использован запасной формат, основываясь на опции fallbackLocale конструктора VueI18n.

Если второй аргумент format указан объектом, то в нём должны быть следующие свойства:

  • key {Path}: опционально, форматируемое число
  • locale {Locale}: опционально, локализация
  • compactDisplay {string}: опционально, опция форматирования чисел
  • currency {string}: опционально, опция форматирования чисел
  • currencyDisplay {string}: опционально, опция форматирования чисел
  • currencySign {string}: опционально, опция форматирования чисел
  • localeMatcher {string}: опционально, опция форматирования чисел
  • notation {string}: опционально, опция форматирования чисел
  • numberingSystem {string}: опционально, опция форматирования чисел
  • signDisplay {string}: опционально, опция форматирования чисел
  • style {string}: опционально, опция форматирования чисел
  • unit {string}: опционально, опция форматирования чисел
  • unitDisplay {string}: опционально, опция форматирования чисел
  • useGrouping {boolean}: опционально, опция форматирования чисел
  • minimumIntegerDigits {string}: опционально, опция форматирования чисел
  • minimumFractionDigits {string}: опционально, опция форматирования чисел
  • maximumFractionDigits {string}: опционально, опция форматирования чисел
  • minimumSignificantDigits {string}: опционально, опция форматирования чисел
  • maximumSignificantDigits {string}: опционально, опция форматирования чисел

Любые указанные опции форматирования числа будут иметь приоритет над значениями numberFormats из конструктора VueI18n.

Совет

Обратите внимание, что в хуках жизненного цикла контекст должен быть экземпляром компонента (например в опции data, const $n = this.$n.bind(this)).

# Внедряемые свойства

# $i18n

  • Тип: I18n

  • Только для чтения

Получение экземпляра VueI18n, если был определён.

Если в компоненте указана опция i18n, то получение экземпляра VueI18n компонента. В противном случае, получение корневого экземпляра VueI18n.

# Класс VueI18n

Класс VueI18n реализует интерфейс I18n из определений flowtype (opens new window)

# Статические свойства

# version

  • Тип: string

Версия vue-i18n.

# availabilities

🆕 Добавлено в версии 7.0+

  • Тип: IntlAvailability

Проверка доступности следующих возможностей интернационализации:

  • {boolean} dateTimeFormat: форматирование дат для локалей

  • {boolean} numberFormat: форматирование чисел для локалей

Указанные выше возможности интернационализации зависят от окружения браузера (opens new window), в котором реализован ECMAScript Internationalization API (ECMA-402).

# Опции конструктора

Можно указывать некоторые опции конструктора I18nOptions, основываясь на определениях flowtype (opens new window)

# locale

  • Тип: Locale

  • По умолчанию: 'en-US'

Локаль используемая для локализации. Если локаль содержит территорию и диалект, то эта локаль явно определяет запасную локализацию.

# fallbackLocale

  • Тип: FallbackLocale

  • По умолчанию: false

Запасная локаль для локализации. Подробнее в разделе Запасная локализация.

# messages

  • Тип: LocaleMessages

  • По умолчанию: {}

Сообщения локализации для локали.

# dateTimeFormats

🆕 Добавлено в версии 7.0+

  • Тип: DateTimeFormats

  • По умолчанию: {}

Форматы дат для локализации.

# numberFormats

🆕 Добавлено в версии 7.0+

  • Тип: NumberFormats

  • По умолчанию: {}

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

# availableLocales

🆕 Добавлено в версии 8.9.0+

  • Тип: Locale[]

  • По умолчанию: []

  • Примеры: ["en", "ru"]

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

# formatter

  • Тип: Formatter

  • По умолчанию: Встроенный formatter

Метод форматирования, реализующий интерфейс Formatter.

# modifiers

🆕 Добавлено в версии 8.15.0+

  • Тип: Modifiers

  • По умолчанию: модификаторы lower и upper

Функции модификаторов для связанных сообщений

# missing

  • Тип: MissingHandler

  • По умолчанию: null

Обработчик для отсутствующих сообщений локализации. Обработчик будет вызван с локалью, ключом сообщения локализации и значениями values.

Если указан этот обработчик и произойдёт попытка доступа к отсутствующему сообщению локализации, то предупреждения в консоли не будет.

# fallbackRoot

  • Тип: Boolean

  • По умолчанию: true

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

При значении false будет выбрасываться предупреждение и возвращаться ключ.

# fallbackRootWithEmptyString

🆕 Добавлено в версии 8.26+

  • Тип: Boolean

  • По умолчанию: true

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

Обратите внимание, что поведение по умолчанию в vue-i18n 9.x заключается в том, чтобы не возвращаться к корневому каталогу для локального сообщения, которое является пустой строкой.

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

# sync

  • Тип: Boolean

  • По умолчанию: true

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

При значении false, независимо от локали определённой на корневом уровне, будет использоваться локаль установленная в компоненте.

# silentTranslationWarn

6.1+, 🆙 8.13

  • Тип: Boolean | RegExp

  • По умолчанию: false

Отключение предупреждений, отображаемых при неудаче локализации.

При значении true, отключаются предупреждения об ошибках локализации. Если использовать регулярное выражение, то можно отключать предупреждения об ошибках, которые будут соответствовать key (например, $t).

# silentFallbackWarn

🆕 Добавлено в версии 8.8+, 🆙 8.13

  • Тип: Boolean | RegExp

  • По умолчанию: false

Отключение предупреждений при использовании запасной локали из fallbackLocale или root.

При значении true предупреждения будут генерироваться только если недоступна локализация вообще, а не для случаев использования запасной локали. При использовании регулярного выражения можно отключать предупреждения которые будут соответствовать key (например, $t).

# pluralizationRules

8.5+

  • Тип: PluralizationRules

  • По умолчанию: {}

Набор правил для плюрализации в следующем формате:

  {
+    // Ключ - локаль для которой будет применяться правило.
+    // Value - функция для получения индекса варианта плюрализации от текущего числа и заданного количества вариантов. (См. функцию getChoiceIndex)
+    'pt': function(choice, choiceIndex) => Number/* index of the plural word */;
+    'ru': function(choice, choiceIndex) => Number/* index of the plural word */;
+    'en': function(choice, choiceIndex) => Number/* index of the plural word */;
+    'jp': function(choice, choiceIndex) => Number/* index of the plural word */;
+  }
+

# preserveDirectiveContent

Добавлено в версии 8.7+

  • Тип: Boolean

  • По умолчанию: false

Определяет должен ли элемент директивы v-t сохранять textContent после того как директива будет снята с элемента.

# warnHtmlInMessage

Добавлено в версии 8.11+

  • Тип: WarnHtmlInMessageLevel

  • По умолчанию: off

Разрешить ли использование HTML-форматирования в сообщениях локализации. См. также свойство warnHtmlInMessage.

Внимание!

Со следующей мажорной версии значение по умолчанию warnHtmlInMessage будет warn.

# sharedMessages

Добавлено в версии 8.12+

  • Тип: LocaleMessages

  • По умолчанию: undefined

Общие сообщения локализации при локализации в компонентах. Подробнее в разделе Локализация на основе компонентов.

# postTranslation

Добавлено в версии 8.16+

  • Тип: PostTranslationHandler

  • По умолчанию: null

Пост-обработчик локализации. Выполняется после вызова $t, t, $tc и tc.

Может пригодиться при необходимости дополнительно обработать итоговый текст перевода, например избавиться от висящих пробелов.

# componentInstanceCreatedListener

Добавлено в версии 8.18+

  • Тип: ComponentInstanceCreatedListener

  • По умолчанию: null

Обработчик получения уведомления о создании локального экземпляра компонента. Вызывается с новым и старым (корневыми) экземплярами VueI18n.

Обработчик может потребоваться при расширении корневого экземпляра VueI18n и необходимости ожидания для применения этих расширений к локальному экземпляру компонента.

# escapeParameterHtml

Добавлено в версии 8.22+

  • Тип: Boolean

  • По умолчанию: false

Если escapeParameterHtml установлен в значение true, то параметры интерполяции будут экранированы перед переводом сообщения. Это полезно, когда результат перевода используется в v-html и текст для перевода содержит HTML-разметку (например, <b> вокруг предоставленного пользователем значения). Этот шаблон в основном предназначен для случаев, когда передаются предварительно скомпилированные текстовые строки в компоненты UI.

Процесс экранирования включает в себя замену следующих символов на соответствующие HTML-сущности: <, >, ", '.

Установка escapeParameterHtml в значение true не должна нарушать существующую функциональность, а предоставит защиту от векторов атаки типа XSS.

# Свойства

# locale

  • Тип: Locale

  • Чтение/Запись

Локаль используемая для локализации. Если локаль содержит территорию и диалект, то эта локаль неявно указывает на запасные варианты.

# fallbackLocale

  • Тип: FallbackLocale

  • Чтение/Запись

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

# messages

  • Тип: LocaleMessages

  • Только для чтения

Переведённые сообщения используемые для локализации.

# dateTimeFormats

🆕 Добавлено в версии 7.0+

  • Тип: DateTimeFormats

  • Только для чтения

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

# numberFormats

🆕 Добавлено в версии 7.0+

  • Тип: NumberFormats

  • Только для чтения

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

# missing

  • Тип: MissingHandler

  • Чтение/Запись

Обработчик для отсутствующих ключей локализаций.

# formatter

  • Тип: Formatter

  • Чтение/Запись

Метод форматирования, который реализует интерфейс Formatter.

# silentTranslationWarn

6.1+, 🆙 8.13

  • Тип: Boolean | RegExp

  • Чтение/Запись

Отключение предупреждений выводимых при ошибке локализации.

# silentFallbackWarn

🆕 Добавлено в версии 8.8+, 🆙 8.13

  • Тип: Boolean | RegExp

  • Чтение/Запись

Отключение предупреждений выводимых при ошибке использования запасной локализации.

# pluralizationRules

8.5+

  • Тип: PluralizationRules

  • Чтение/Запись

Набор зависимых от локали правил плюрализации.

# preserveDirectiveContent

Добавлено в версии 8.7+

  • Тип: Boolean

  • Чтение/Запись

Должен ли элемент директивы v-t сохранять textContent после того как директива снята с элемента.

# warnHtmlInMessage

Добавлено в версии 8.11+

  • Тип: WarnHtmlInMessageLevel

  • Чтение/Запись

Разрешить ли использование HTML-форматирования в сообщениях локализации.

При установке warn или error проверяются сообщения локализации экземпляра VueI18n.

При установке warn выводятся предупреждения в консоль.

При установке error генерируется Error.

В качестве значения по умолчанию в экземпляре VueI18n установлено off.

# postTranslation

Добавлено в версии 8.16+

  • Тип: PostTranslationHandler

  • Чтение/Запись

Обработчик для пост-обработки перевода.

# Методы

# getChoiceIndex

  • Аргументы:

    • {number} choice
    • {number} choicesLength
  • Возвращает: finalChoice {number}

Получение индекса для плюрализации текущего числа и заданного количества вариантов. Реализация может быть переопределена через изменение прототипа:

VueI18n.prototype.getChoiceIndex = /* пользовательская реализация */
+

Однако в большинстве случаев достаточно передать нужную функцию в pluralizationRules опцию конструктора.

# getLocaleMessage( locale )

  • Аргументы:

    • {Locale} locale
  • Возвращает: LocaleMessageObject

Получение сообщений локализации для локали.

# setLocaleMessage( locale, message )

  • Аргументы:

    • {Locale} locale
    • {LocaleMessageObject} message

Установка сообщений локализации для локали.

ПРИМЕЧАНИЕ

Добавлено в версии 8.11+

При использовании warn или error в свойстве warnHtmlInMessage, при выполнении этого метода будет проверено используется ли HTML-форматирование для сообщения локализации.

# mergeLocaleMessage( locale, message )

6.1+

  • Аргументы:

    • {Locale} locale
    • {LocaleMessageObject} message

Объединение указанных сообщений локализации с сообщениями локализации локали.

ПРИМЕЧАНИЕ

Добавлено в версии 8.11+

При использовании warn или error в свойстве warnHtmlInMessage, при выполнении этого метода будет проверено используется ли HTML-форматирование для сообщения локализации.

# t( key, [locale], [values] )

  • Аргументы:

    • {Path} key: обязательный
    • {Locale} locale: опционально
    • {Array | Object} values: опционально
  • Возвращает: : TranslateResult

Аналогично функции возвращаемой методом $t. Подробнее см. $t.

# tc( key, [choice], [values] )

  • Аргументы:

    • {Path} key: обязательный
    • {number} choice: опционально, по умолчанию 1
    • {string | Array | Object} values: опционально
  • Возвращает: TranslateResult

Аналогично функции возвращаемой методом $tc. Подробнее см. $tc.

# te( key, [locale] )

  • Аргументы:

    • {string} key: обязательный
    • {Locale} locale: опционально
  • Возвращает: boolean

Проверяет существует ли указанный ключ в глобальных сообщениях локализации. Если указать locale, проверка будет осуществляться в сообщениях локализации locale.

# getDateTimeFormat ( locale )

🆕 Добавлено в версии 7.0+

  • Аргументы:

    • {Locale} locale
  • Возвращает: DateTimeFormat

Получение форматов форматирования дат локализации.

# setDateTimeFormat ( locale, format )

🆕 Добавлено в версии 7.0+

  • Аргументы:

    • {Locale} locale
    • {DateTimeFormat} format

Установка форматов форматирования дат для локализации.

# mergeDateTimeFormat ( locale, format )

🆕 Добавлено в версии 7.0+

  • Аргументы:

    • {Locale} locale
    • {DateTimeFormat} format

Объединение указанных форматов форматирования дат с форматами локализации.

# d( value, [key], [locale] )

🆕 Добавлено в версии 7.0+

  • Аргументы:

    • {number | Date} value: обязательный
    • {Path | Object} key: опционально
    • {Locale | Object} locale: опционально
  • Возвращает: DateTimeFormatResult

Аналогично функции возвращаемой методом $d. Подробнее см. $d.

# getNumberFormat ( locale )

🆕 Добавлено в версии 7.0+

  • Аргументы:

    • {Locale} locale
  • Возвращает: NumberFormat

Получение форматов форматирования чисел для локализации.

# setNumberFormat ( locale, format )

🆕 Добавлено в версии 7.0+

  • Аргументы:

    • {Locale} locale
    • {NumberFormat} format

Установка форматов форматирования чисел для локализации.

# mergeNumberFormat ( locale, format )

🆕 Добавлено в версии 7.0+

  • Аргументы:

    • {Locale} locale
    • {NumberFormat} format

Объединение указанных форматов форматирования чисел с форматами локализации.

# n( value, [format], [locale] )

🆕 Добавлено в версии 7.0+

  • Аргументы:

    • {number} value: обязательный
    • {Path | Object} format: опционально
    • {Locale} locale: опционально
  • Возвращает: NumberFormatResult

Аналогично функции возвращаемой методом $n. Подробнее см. $n.

# Директивы

🆕 Добавлено в версии 7.3+

# v-t

  • Ожидает: string | Object

  • Модификаторы:

    • .preserve: (8.7.0+) сохраняет textContent элемента при снятии директивы с элемента.
  • Подробности:

Обновление textContent элемента, который был переведён с помощью сообщений локализации. Можно использовать строковый или объектный синтаксис. Строковый синтаксис может быть задан в качестве пути к сообщению локализации. При использовании объектного синтаксиса необходимо указать следующие свойства:

  • path: обязательный, ключ сообщения локализации
  • locale: опционально, локализация
  • args: опционально, для списка или именованного форматирования

ПРИМЕЧАНИЕ

По умолчанию значение textContent элемента удаляется при снятии директивы v-t. Это может быть нежелательной ситуацией например при анимировании списков (opens new window). Для сохранения данных textContent после снятия директивы следует использовать модификатор .preserve или глобальную опцию preserveDirectiveContent.

  • Примеры:
<!-- строковый синтаксис: литерал -->
+<p v-t="'foo.bar'"></p>
+
+<!-- строковый синтаксис: привязка к данным -->
+<p v-t="msg"></p>
+
+<!-- объектный синтаксис: литерал -->
+<p v-t="{ path: 'hi', локализация: 'ru', args: { name: 'kazupon' } }"></p>
+
+<!-- объектный синтаксис: привязка к данным -->
+<p v-t="{ path: greeting, args: { name: fullName } }"></p>
+
+<!-- с модификатором preserve -->
+<p v-t.preserve="'foo.bar'"></p>
+

# Компоненты

# Функциональный компонент i18n

🆕 Добавлено в версии 7.0+

# Входные параметры:

  • path {Path}: обязательный, путь к сообщению локализации
  • locale {Locale}: опционально, локализация
  • tag {string | boolean | Object}: опционально, по умолчанию 'span'
  • places {Array | Object}: опционально (7.2+)

Внимание!

Со следующей мажорной версии опция places будет удалена. Используйте синтаксис слотов.

# Использование:

<div id="app">
+  <!-- ... -->
+  <i18n path="term" tag="label" for="tos">
+    <a :href="url" target="_blank">{{ $t('tos') }}</a>
+  </i18n>
+  <!-- ... -->
+</div>
+
const messages = {
+  en: {
+    tos: 'Term of Service',
+    term: 'I accept xxx {0}.'
+  },
+  ru: {
+    tos: 'Условия обслуживания',
+    term: 'Я соглашаюсь с xxx {0}.'
+  }
+}
+
+const i18n = new VueI18n({
+  locale: 'en',
+  messages
+})
+new Vue({
+  i18n,
+  data: {
+    url: '/term'
+  }
+}).$mount('#app')
+

# См. также:

Интерполяция компонента

# Функциональный компонент i18n-n

🆕 Добавлено в версии 8.10+

# Входные параметры:

  • value {number}: обязательный, число для форматирования
  • format {string | NumberFormatOptions}: опционально, форматируемое число или объект с указанными опциями форматирования
  • locale {Locale}: опционально, локализация
  • tag {string | boolean | Object}: опционально, по умолчанию 'span'

# Использование:

<div id="app">
+  <!-- ... -->
+  <i18n-n :value="money" format="currency" tag="label">
+    <span v-slot:currency="slotProps" class="font-weight: bold">
+      {{ slotProps.currency }}
+    <span>
+  </i18n-n>
+  <!-- ... -->
+</div>
+
var numberFormats = {
+  'en-US': {
+    currency: {
+      style: 'currency',
+      currency: 'USD'
+    }
+  },
+  'ru-RU': {
+    currency: {
+      style: 'currency',
+      currency: 'RUB'
+    }
+  }
+}
+
+const i18n = new VueI18n({
+  locale: 'en-US',
+  numberFormats
+})
+
+new Vue({
+  i18n,
+  data: {
+    money: 10234
+  }
+}).$mount('#app')
+

# Слоты с ограниченной областью видимости

Функциональный компонент <i18n-n> может принимать различные слоты с ограниченной областью видимости. Список поддерживаемых имён слотов основан на выходных типах Intl.NumberFormat.formatToParts() (opens new window):

  • currency
  • decimal
  • fraction
  • group
  • infinity
  • integer
  • literal
  • minusSign
  • nan
  • plusSign
  • percentSign

Каждый из слотов предоставляет доступ к значениям трёх параметров:

  • [slotName] {FormattedNumberPartType}: параметр с тем же именем, что и имя слота (например, integer)
  • index {Number}: индекс конкретной части в массиве частей числа
  • parts {Array}: массив со всеми отформатированными частями числа

# См. также:

Локализация чисел

# Специальные атрибуты

# place

🆕 Добавлено в версии 7.2+

# Ожидает: {number | string}

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

Подробнее об использовании в разделе по ссылке ниже.

# См. также:

Интерполяция компонента

+ + + diff --git a/ru/guide/component.html b/ru/guide/component.html new file mode 100644 index 000000000..55febbf15 --- /dev/null +++ b/ru/guide/component.html @@ -0,0 +1,195 @@ + + + + + + Локализация на основе компонентов | Vue I18n + + + + + + + + + +

# Локализация на основе компонентов

В основном данные для локализации (например, locale,messages, и т.д.) задаются опциями конструктора экземпляра VueI18n и устанавливаются через свойство i18n в корневой экземпляр Vue.

Поэтому можно глобально выполнять переводы, используя методы $t или $tc в корневом экземпляре Vue и любом из компонентов в нём. Но также возможно указывать данные для локализации в каждом компоненте в отдельности, что может быть удобнее благодаря компонентно-ориентированному дизайну.

Пример локализации на основе компонентов:

// Установка локализации в корневой экземпляр Vue
+const i18n = new VueI18n({
+  locale: 'ru',
+  messages: {
+    en: {
+      message: {
+        hello: 'hello world',
+        greeting: 'good morning'
+      }
+    },
+    ru: {
+      message: {
+        hello: 'привет мир',
+        greeting: 'доброе утро'
+      }
+    }
+  }
+})
+
+// Определение компонента
+const Component1 = {
+  template: `
+    <div class="container">
+     <p>Component1 locale messages: {{ $t("message.hello") }}</p>
+     <p>Fallback global locale messages: {{ $t("message.greeting") }}</p>
+   </div>`,
+  i18n: {
+    // опция `i18n`, определение данных локализации для компонента
+    messages: {
+      en: { message: { hello: 'hello component1' } },
+      ru: { message: { hello: 'привет component1' } }
+    }
+  }
+}
+
+new Vue({
+  i18n,
+  components: {
+    Component1
+  }
+}).$mount('#app')
+

Шаблон:

<div id="app">
+  <p>{{ $t("message.hello") }}</p>
+  <component1></component1>
+</div>
+

Результат:

<div id="app">
+  <p>привет мир</p>
+  <div class="container">
+    <p>Component1 locale messages: привет component1</p>
+    <p>Fallback global locale messages: доброе утро</p>
+  </div>
+</div>
+

Если компонент не имеет собственного сообщения для локализации, то в качестве запасного выхода он обратится к глобальным данным для локализации. Компонент использует локаль, установленную в корневом экземпляре (в примере выше установлена: locale: 'ru').

Обратите внимание, по умолчанию при обращении к данным корневой локализации будут генерироваться предупреждения в консоли:

[vue-i18n] Value of key 'message.greeting' is not a string!
+[vue-i18n] Fall back to translate the keypath 'message.greeting' with root locale.
+

Чтобы скрыть эти предупреждения (оставив те, что предупреждают о полном отсутствии перевода для данного ключа) установите опцию silentFallbackWarn: true при инициализации экземпляра VueI18n.

Если необходимо осуществлять перевод, основываясь на локали компонента, то это можно сделать с помощью опции sync: false и locale в настройках i18n.

# Общие сообщения локализации для компонентов

Иногда может потребоваться импортировать сообщения локализации в определённых компонентах, чтобы не обращаться к глобальным сообщениям локализации (например, общие сообщения для определённых функций компонентов).

Для этого можно использовать опцию sharedMessages в свойстве i18n компонента.

Пример использования общих сообщений локализации:

export default {
+  en: {
+    buttons: {
+      save: 'Save'
+      // ...
+    }
+  },
+  ru: {
+    buttons: {
+      save: 'Сохранить'
+      // ...
+    }
+  }
+}
+

Компонент:

import commonMessage from './locales/common' // импорт общих сообщений локализации
+
+export default {
+  name: 'ServiceModal',
+  template: `
+    <div class="modal">
+      <div class="body">
+        <p>Это хороший сервис</p>
+      </div>
+      <div class="footer">
+        <button type="button">
+          {{ $t('buttons.save') }}
+        </button>
+      </div>
+    </div>
+  `,
+  i18n: {
+    messages: { ... },
+    sharedMessages: commonMessages
+  }
+}
+

Если указаны опции sharedMessages и messages, то их сообщения будут объединены в сообщения локализации в экземпляре VueI18n этого компонента.

# Локализация в функциональных компонентах

При использовании функционального компонента все данные (включая props, children, slots, parent, и т.д.) передаются через context, в котором содержатся все эти атрибуты. Кроме того отсутствует возможность использовать this, поэтому при использовании vue-i18n с функциональными компонентами следует обращаться к $t как к parent.$t, например так:

...
+<div>
+  <a href="#" target="_blank" rel="noopener noreferrer">
+    <img src="./assets/example.jpg" :alt="parent.$t('message.hello')" />
+  </a>
+</div>
+...
+
+ + + diff --git a/ru/guide/datetime.html b/ru/guide/datetime.html new file mode 100644 index 000000000..2ec0c7158 --- /dev/null +++ b/ru/guide/datetime.html @@ -0,0 +1,147 @@ + + + + + + Локализация дат | Vue I18n + + + + + + + + + +

# Локализация дат

Поддержка с версии

🆕 7.0+

Можно выполнять локализацию дат по соответствующему формату.

Пример формата для дат:

const dateTimeFormats = {
+  'en-US': {
+    short: {
+      year: 'numeric',
+      month: 'short',
+      day: 'numeric'
+    },
+    long: {
+      year: 'numeric',
+      month: 'long',
+      day: 'numeric',
+      weekday: 'long',
+      hour: 'numeric',
+      minute: 'numeric'
+    }
+  },
+  'pt-BR': {
+    short: {
+      year: 'numeric',
+      month: 'short',
+      day: 'numeric'
+    },
+    long: {
+      year: 'numeric',
+      month: 'long',
+      day: 'numeric',
+      weekday: 'long',
+      hour: 'numeric',
+      minute: 'numeric',
+      hour12: true
+    }
+  }
+}
+

Как видно выше, можно определять именованный формат даты (например, short, long и т.д.) используя опции ECMA-402 Intl.DateTimeFormat (opens new window)

После этого, для возможности использования данного формата в сообщениях локализации, необходимо задать опцию dateTimeFormats в конструкторе VueI18n:

const i18n = new VueI18n({
+  dateTimeFormats
+})
+
+new Vue({
+  i18n
+}).$mount('#app')
+

Шаблон:

<div id="app">
+  <p>{{ $d(new Date(), 'short') }}</p>
+  <p>{{ $d(new Date(), 'long', 'pt-BR') }}</p>
+</div>
+

Результат:

<div id="app">
+  <p>Jan 18, 2021</p>
+  <p>domingo, 18 de janeiro de 2021 5:47 AM</p>
+</div>
+
+ + + diff --git a/ru/guide/directive.html b/ru/guide/directive.html new file mode 100644 index 000000000..4978ed6af --- /dev/null +++ b/ru/guide/directive.html @@ -0,0 +1,173 @@ + + + + + + Пользовательская директива | Vue I18n + + + + + + + + + +

# Пользовательская директива

Поддержка с версии

🆕 7.3+

Переводы можно осуществлять не только используя пользовательскую директиву v-t, но и с помощью метода $t.

# Строковый синтаксис

Можно передавать ключ сообщения локализации строкой.

JavaScript:

new Vue({
+  i18n: new VueI18n({
+    locale: 'en',
+    messages: {
+      en: { hello: 'hi there!' },
+      ru: { hello: 'привет всем!' }
+    }
+  }),
+  data: { path: 'hello' }
+}).$mount('#string-syntax')
+

Шаблон:

<div id="string-syntax">
+  <!-- строковый литерал -->
+  <p v-t="'hello'"></p>
+  <!-- привязка пути к сообщению из данных -->
+  <p v-t="path"></p>
+</div>
+

Результат:

<div id="string-syntax">
+  <p>привет всем!</p>
+  <p>привет всем!</p>
+</div>
+

# Объектный синтаксис

Можно использовать объектный синтаксис.

JavaScript:

new Vue({
+  i18n: new VueI18n({
+    locale: 'en',
+    messages: {
+      en: { hello: 'hi {name}!' },
+      ru: { hello: 'привет {name}!' }
+    }
+  }),
+  computed: {
+    nickName() { return 'kazupon' }
+  },
+  data: { path: 'hello' }
+}).$mount('#object-syntax')
+

Шаблон:

<div id="object-syntax">
+  <!-- литерал -->
+  <p v-t="{ path: 'hello', locale: 'ru', args: { name: 'kazupon' } }"></p>
+  <!-- привязка к данным -->
+  <p v-t="{ path: path, args: { name: nickName } }"></p>
+</div>
+

Результат:

<div id="object-syntax">
+  <p>привет、kazupon!</p>
+  <p>hi kazupon!</p>
+</div>
+

# Использование с transition

Поддержка с версии

🆕 8.7+

При использовании директивы v-t на элементе внутри компонента <transition> (opens new window), можно заметить как переведённое сообщение исчезает во время анимации перехода. Это поведение связано с реализацией самого компонента <transition> — все директивы в исчезающем элементе внутри компонента <transition> должны быть уничтожены до начала анимации. Это может привести к мерцанию содержимого на коротких анимациях, но наиболее заметно при длинных анимациях переходов.

Чтобы сохранить содержимое директивы во время анимации перехода, необходимо добавить модификатор .preserve при определении директивы v-t.

Javascript:

new Vue({
+  i18n: new VueI18n({
+    locale: 'en',
+    messages: {
+      en: { preserve: 'with preserve' }
+    }
+  }),
+  data: { toggle: true }
+}).$mount('#in-transitions')
+

Шаблон:

<div id="in-transitions">
+  <transition name="fade">
+    <span v-if="toggle" v-t.preserve="'preserve'"></span>
+  </transition>
+  <button @click="toggle = !toggle">Toggle</button>
+</div>
+

Также можно глобально установить настройку preserveDirectiveContent в экземпляре VueI18n, что повлияет на все директивы v-t без добавления модификатора к ним.

JavaScript:

new Vue({
+  i18n: new VueI18n({
+    locale: 'en',
+    messages: {
+      en: { preserve: 'with preserve' }
+    },
+    preserveDirectiveContent: true
+  }),
+  data: { toggle: true }
+}).$mount('#in-transitions')
+

Шаблон:

<div id="in-transitions">
+  <transition name="fade">
+    <span v-if="toggle" v-t="'preserve'"></span>
+  </transition>
+  <button @click="toggle = !toggle">Toggle</button>
+</div>
+

Подробнее о примерах выше можно изучить здесь (opens new window)

# $t или v-t

# $t

$t — это метод, добавленный в экземпляр Vue. У него следующие плюсы и минусы:

# Плюсы

Предоставляет гибкость в использовании синтаксиса фигурных скобок {{}} в шаблонах, а также применять в вычисляемых свойствах и методах экземпляра Vue.

# Минусы

$t выполняется каждый раз когда происходит перерисовка, поэтому у него есть расходы на осуществление перевода.

# v-t

v-t — пользовательская директива. У неё следующие плюсы и минусы:

# Плюсы

v-t имеет лучшую производительность в сравнении с методом $t, благодаря кэшу в пользовательской директиве после выполнения перевода. Также можно реализовать предварительный перевод с помощью модуля для компилятора Vue, который предоставляет плагин vue-i18n-extensions (opens new window).

Таким образом, можно достичь большей оптимизации производительности.

# Минусы

v-t нельзя использовать также гибко, как $t, и это добавляет сложности. Перевод с помощью v-t вставляется в textContent элемента. Также, при использовании рендеринга на стороне сервера необходимо установить пользовательскую директиву (opens new window) через опцию directives функции createRenderer.

+ + + diff --git a/ru/guide/fallback.html b/ru/guide/fallback.html new file mode 100644 index 000000000..b590c7b13 --- /dev/null +++ b/ru/guide/fallback.html @@ -0,0 +1,146 @@ + + + + + + Запасная локализация | Vue I18n + + + + + + + + + +

# Запасная локализация

Вкратце: указывайте fallbackLocale: '<lang>' для определения языка, который будет использоваться, если нет перевода в выбранной локализации.

# Неявное определение запасных локализаций при использовании локалей

Если locale содержит территорию и опционально диалект, то неявно будут определены автоматически запасные локали.

Например для de-DE-bavarian в качестве запасных будут считаться следующие:

  1. de-DE-bavarian
  2. de-DE
  3. de

Для отключения автоматического определения запасных локалей укажите символ !, например de-DE!

# Явное определение одной локали запасной локализации

Иногда не все ключи сообщений переведены на другие языки. В примере ниже, сообщение для ключа hello доступно в английской локали, но отсутствует в русской:

const messages = {
+  en: {
+    hello: 'Hello, world!'
+  },
+  ru: {
+    // упс, не все переведено
+  }
+}
+

Если хочется использовать сообщения локализации из en, когда перевод отсутствует в нужной локализации, то следует указать опцию fallbackLocale в конструкторе VueI18n:

const i18n = new VueI18n({
+  locale: 'ru',
+  fallbackLocale: 'en',
+  messages
+})
+

Шаблон:

<p>{{ $t('hello') }}</p>
+

Результат:

<p>Hello, world!</p>
+

По умолчанию, если использовались сообщения запасной локализации из fallbackLocale, то в консоли будут выведены соответствующие предупреждения:

[vue-i18n] Value of key 'hello' is not a string!
+[vue-i18n] Fall back to translate the keypath 'hello' with 'en' locale.
+

Чтобы скрыть такие предупреждения (оставив при этом те, в случаях полного отсутствия переводов для данного ключа) установите silentFallbackWarn: true при инициализации экземпляра VueI18n.

# Явное определение запасной локали с помощью массива

Можно указать более одной запасной локализации с помощью массива. Например:

fallbackLocale: ['ru', 'en'],
+

# Явное определение запасной локали с помощью объекта

Более сложный алгоритм принятия решений для определения запасной локали можно реализовать с помощью карты принятия решений в виде объекта.

Например для подобного объекта:

fallbackLocale: {
+  /* 1 */ 'de-CH':   ['fr', 'it'],
+  /* 2 */ 'zh-Hant': ['zh-Hans'],
+  /* 3 */ 'es-CL':   ['es-AR'],
+  /* 4 */ 'es':      ['en-GB'],
+  /* 5 */ 'pt':      ['es-AR'],
+  /* 6 */ 'default': ['en', 'ru']
+},
+

Будут следующие цепочки выбора запасной локали:

Локаль Цепочка выбора
'de-CH' de-CH > fr > it > en > ru
'de' de > en > ru
'zh-Hant' zh-Hant > zh-Hans > zh > en > ru
'es-SP' es-SP > es > en-GB > en > ru
'es-SP!' es-SP > en > ru
'fr' fr > en > ru
'pt-BR' pt-BR > pt > es-AR > es > en-GB > en > ru
'es-CL' es-CL > es-AR > es > en-GB > en > ru

# Резервная интерполяция

Вкратце: установите formatFallbackMessages: true чтобы выполнять интерполяции шаблона по ключам перевода, когда в выбранном языке отсутствует данный ключ для перевода.

Так как ключи переводов являются строками, то можно использовать само сообщение в качестве ключа (для определённого языка). Например:

const messages = {
+  ru: {
+    'Hello, world!': 'Привет мир!'
+  }
+}
+

Это может быть полезным, потому что не нужно будет указывать перевод для строки "Hello, world!" в английской локализации.

Фактически, можно указывать даже параметры в ключе. Вместе с formatFallbackMessages: true это позволит опустить создание шаблонов для «базового» языка; потому что его ключи уже находятся в шаблоне.

const messages = {
+  ru: {
+    'Hello {name}': 'Здравствуйте {name}'
+  }
+}
+
+const i18n = new VueI18n({
+  locale: 'ru',
+  fallbackLocale: 'en',
+  formatFallbackMessages: true,
+  messages
+})
+

Шаблон:

<p>{{ $t('Hello {name}', { name: 'John' }}) }}</p>
+<p>{{ $t('The weather today is {condition}!', { condition: 'sunny' }) }}</p>
+

Результат:

<p>Здравствуйте, John</p>
+<p>The weather today is sunny!</p>
+
+ + + diff --git a/ru/guide/formatting.html b/ru/guide/formatting.html new file mode 100644 index 000000000..24b26658a --- /dev/null +++ b/ru/guide/formatting.html @@ -0,0 +1,221 @@ + + + + + + Формат сообщений локализации | Vue I18n + + + + + + + + + +

# Формат сообщений локализации

# Именованный формат

Сообщения локализации:

const messages = {
+  en: {
+    message: {
+      hello: '{msg} world'
+    }
+  },
+  ru: {
+    message: {
+      hello: '{msg} мир'
+    }
+  }
+}
+

Шаблон:

<p>{{ $t('message.hello', { msg: 'привет' }) }}</p>
+

Результат:

<p>привет мир</p>
+

# Формат списков

Сообщения локализации:

const messages = {
+  en: {
+    message: {
+      hello: '{0} world'
+    }
+  },
+  ru: {
+    message: {
+      hello: '{0} мир'
+    }
+  }
+}
+

Шаблон:

<p>{{ $t('message.hello', ['привееет']) }}</p>
+

Результат:

<p>привееет мир</p>
+

Форматирование списков также принимает объекты, соответствующие по структуре массиву:

<p>{{ $t('message.hello', {'0': 'привееет'}) }}</p>
+

Результат:

<p>привееет мир</p>
+

# HTML формат

Обратите внимание

⚠️ Динамическая локализация произвольного HTML на вебсайте очень опасна, потому что легко может привести к XSS-уязвимостям. Используйте HTML-интерполяцию только для доверенного контента и никогда для пользовательского.

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

Обратите внимание

🆕 Добавлено в версии 8.11+

Можно управлять использованием HTML форматирования. Для подробностей см. опцию конструктора warnHtmlInMessage и свойства API.

Иногда требуется отобразить сообщение локализации HTML-кодом, а не статической строкой.

const messages = {
+  en: {
+    message: {
+      hello: 'hello <br> world'
+    }
+  },
+  ru: {
+    message: {
+      hello: 'привет <br> мир'
+    }
+  }
+}
+

Шаблон:

<p v-html="$t('message.hello')"></p>
+

Результат (вместо отформатированного сообщения)

<p>
+  привет
+  <!-- <br> существует, но отрисован как html, а не строкой -->
+  мир
+</p>
+

# Формат ruby on rails i18n

Сообщения локализации:

const messages = {
+  en: {
+    message: {
+      hello: '%{msg} world'
+    }
+  },
+  ru: {
+    message: {
+      hello: '%{msg} мир'
+    }
+  }
+}
+

Шаблон:

<p>{{ $t('message.hello', { msg: 'привет' }) }}</p>
+

Результат:

<p>привет мир</p>
+

# Пользовательский формат

Иногда может потребоваться реализовать локализацию для собственного формата сообщений (например, использовать синтаксиса сообщений ICU (opens new window)).

Реализовать это можно с помощью специального пользовательского метода форматирования, который должен реализовать интерфейс Formatter (opens new window).

Пример пользовательского метода форматирования с синтаксисом класса ES2015:

// Реализация пользовательского Formatter
+class CustomFormatter {
+  constructor(options) {
+    // ...
+  }
+
+  //
+  // interpolate
+  //
+  // @param {string} message
+  //   строка или список или именованный формат
+  //   напр.
+  //   - именованный формат: 'Hi {name}'
+  //   - формат списка: 'Hi {0}'
+  //
+  // @param {Object | Array} values
+  //   значения интерполяции `message`.
+  //   переданные значения с `$t`, `$tc` и функциональным компонентом `i18n`.
+  //   напр.
+  //   - $t('hello', { name: 'Alex' }) -> переданные значения: Object `{ name: 'Alex' }`
+  //   - $t('hello', ['Alex']) -> переданные значения: Array `['Alex']`
+  //   - функциональный компонент `i18n` (интерполяция в компоненте)
+  //     <i18n path="hello">
+  //       <p>Alex</p>
+  //       <p>how are you?</p>
+  //     </i18n>
+  //     -> переданные значения: Array (included VNode):
+  //        `[VNode{ tag: 'p', text: 'Alex', ...}, VNode{ tag: 'p', text: 'how are you?', ...}]`
+  //
+  // @return {Array<any>}
+  //   интерполированные значения. Они необходимы чтобы вернуть следующее:
+  //   - массив строк, когда используется `$t` или `$tc`.
+  //   - массив, включая объект VNode, когда используется функциональный компонент `i18n`.
+  //
+  interpolate(message, values) {
+    // реализация логики интерполяции
+    // ...
+
+    // возвращаем интерполированный массив
+    return ['resolved message string']
+  }
+}
+
+// Регистрация через опцию `formatter`
+const i18n = new VueI18n({
+  locale: 'en-US',
+  formatter: new CustomFormatter(/* опции конструктора */),
+  messages: {
+    'en-US': {
+      // ...
+    },
+    'ru-RU': {
+      // ...
+    }
+    // ...
+  }
+})
+
+// Запускаем приложение!
+new Vue({ i18n }).$mount('#app')
+

Также посмотрите официальный пример пользовательского метода форматирования (opens new window).

+ + + diff --git a/ru/guide/hot-reload.html b/ru/guide/hot-reload.html new file mode 100644 index 000000000..8df8e625e --- /dev/null +++ b/ru/guide/hot-reload.html @@ -0,0 +1,181 @@ + + + + + + Горячая перезагрузка переводов | Vue I18n + + + + + + + + + +

# Горячая перезагрузка переводов

С помощью функции Webpack для горячей перезагрузки модулей (HMR) (opens new window) можно отслеживать изменения в файлах локализации и осуществлять их горячую перезагрузку в приложении.

# Простой пример

Для статичного набора локалей, можно явно указать горячую перезагрузку этих переводов:

import Vue from "vue"
+import VueI18n from "vue-i18n"
+import en from './en'
+import ru from './ru'
+
+const messages = {
+  en,
+  ru
+}
+
+// Экземпляр VueI18n
+const i18n = new VueI18n({
+  locale: 'en',
+  messages
+})
+
+// Запускаем приложение
+const app = new Vue({
+  i18n
+  // ...
+}).$mount('#app')
+
+// Добавляем горячую перезагрузку сообщений локализации
+if (module.hot) {
+  module.hot.accept(['./en', './ru'], function() {
+    i18n.setLocaleMessage('en', require('./en').default)
+    i18n.setLocaleMessage('ru', require('./ru').default)
+    // Или добавляем горячую перезагрузку через свойство $i18n
+    // app.$i18n.setLocaleMessage('en', require('./en').default)
+    // app.$i18n.setLocaleMessage('ru', require('./ru').default)
+  })
+}
+

# Продвинутый пример

Если требуется поддержка изменяющегося набор переводов, можно реализовать горячую перезагрузку для всех локалей динамически через require.context:

import Vue from "vue";
+import VueI18n from "vue-i18n";
+
+Vue.use(VueI18n);
+
+// Загрузка всех локалей и сохранение контекста
+function loadMessages() {
+  const context = require.context("./locales", true, /[a-z0-9-_]+\.json$/i);
+
+  const messages = context
+    .keys()
+    .map((key) => ({ key, locale: key.match(/[a-z0-9-_]+/i)[0] }))
+    .reduce(
+      (messages, { key, locale }) => ({
+        ...messages,
+        [locale]: context(key),
+      }),
+      {}
+    );
+
+  return { context, messages };
+}
+
+const { context, messages } = loadMessages();
+
+// Экземпляр VueI18n
+const i18n = new VueI18n({
+  locale: "en",
+  messages,
+});
+
+// Запускаем приложение
+const app = new Vue({
+  i18n,
+  // ...
+}).$mount('#app');
+
+// Добавляем горячую перезагрузку сообщений локализации
+if (module.hot) {
+  module.hot.accept(context.id, () => {
+    const { messages: newMessages } = loadMessages();
+
+    Object.keys(newMessages)
+      .filter((locale) => messages[locale] !== newMessages[locale])
+      .forEach((locale) => {
+        messages[locale] = newMessages[locale];
+        i18n.setLocaleMessage(locale, messages[locale]);
+      });
+  });
+}
+
+ + + diff --git a/ru/guide/interpolation.html b/ru/guide/interpolation.html new file mode 100644 index 000000000..538f0b750 --- /dev/null +++ b/ru/guide/interpolation.html @@ -0,0 +1,249 @@ + + + + + + Интерполяция компонента | Vue I18n + + + + + + + + + +

# Интерполяция компонента

# Базовое использование

Поддержка с версии

🆕 7.0+

Иногда требуется перевести сообщения в которых есть HTML теги или компоненты. Например:

<p>I accept xxx <a href="/term">Terms of Service Agreement</a></p>
+

Для такого сообщения, если хотим использовать $t, то, вероятно, попробуем достичь скомпоновав из следующих сообщений локализации:

const messages = {
+  en: {
+    term1: "I Accept xxx's",
+    term2: 'Terms of Service Agreement'
+  }
+}
+

И в итоге шаблон станет выглядеть так:

<p>{{ $t('term1') }}<a href="/term">{{ $t('term2') }}</a></p>
+

Результат:

<p>I accept xxx <a href="/term">Terms of Service Agreement</a></p>
+

Это выглядит очень громоздко, но если перенести тег <a> в сообщение локализации, то добавится вероятность XSS-уязвимости из-за применения v-html="$t('term')".

Этого можно избежать воспользовавшись функциональным компонентом i18n. Например:

<div id="app">
+  <!-- ... -->
+  <i18n path="term" tag="label" for="tos">
+    <a :href="url" target="_blank">{{ $t('tos') }}</a>
+  </i18n>
+  <!-- ... -->
+</div>
+
const messages = {
+  en: {
+    tos: 'Term of Service',
+    term: 'I accept xxx {0}.'
+  },
+  ru: {
+    tos: 'Условия обслуживания',
+    term: 'Я соглашаюсь с xxx {0}.'
+  }
+}
+
+const i18n = new VueI18n({
+  locale: 'en',
+  messages
+})
+new Vue({
+  i18n,
+  data: {
+    url: '/term'
+  }
+}).$mount('#app')
+

Результат:

<div id="app">
+  <!-- ... -->
+  <label for="tos">
+    I accept xxx <a href="/term" target="_blank">Term of Service</a>.
+  </label>
+  <!-- ... -->
+</div>
+

Подробнее о примере можно изучить здесь (opens new window)

Потомки функционального компонента i18n интерполируют сообщения локализации по входному параметру path.

В примере выше:

<a :href="url" target="_blank">{{ $t('tos') }}</a>

интерполируется с сообщением локализации term.

В примере выше интерполяция компонента использует формат в виде списка. Потомки функционального компонента i18n интерполируются по порядку их появления.

Определить тип корневого элемента можно указать с помощью входного параметра tag. Если входной параметр не указан, то по умолчанию будет 'span'. Также можно указать значение false, чтобы вставлять дочерние элементы без создания и оборачивания в корневой.

# Использование синтаксиса слотов

Поддержка с версии

🆕 8.14+

Гораздо удобнее использовать синтаксис именованных слотов. Например:

<div id="app">
+  <!-- ... -->
+  <i18n path="info" tag="p">
+    <template v-slot:limit>
+      <span>{{ changeLimit }}</span>
+    </template>
+    <template v-slot:action>
+      <a :href="changeUrl">{{ $t('change') }}</a>
+    </template>
+  </i18n>
+  <!-- ... -->
+</div>
+
const messages = {
+  en: {
+    info: 'You can {action} until {limit} minutes from departure.',
+    change: 'change your flight',
+    refund: 'refund the ticket'
+  }
+}
+
+const i18n = new VueI18n({
+  locale: 'en',
+  messages
+})
+
+new Vue({
+  i18n,
+  data: {
+    changeUrl: '/change',
+    refundUrl: '/refund',
+    changeLimit: 15,
+    refundLimit: 30
+  }
+}).$mount('#app')
+

Результат:

<div id="app">
+  <!-- ... -->
+  <p>
+    You can <a href="/change">change your flight</a> until
+    <span>15</span> minutes from departure.
+  </p>
+  <!-- ... -->
+</div>
+

С версии Vue 2.6 можно использовать сокращённый синтаксис слотов в шаблонах:

<div id="app">
+  <!-- ... -->
+  <i18n path="info" tag="p">
+    <template #limit>
+      <span>{{ changeLimit }}</span>
+    </template>
+    <template #action>
+      <a :href="changeUrl">{{ $t('change') }}</a>
+    </template>
+  </i18n>
+  <!-- ... -->
+</div>
+

Ограничение

⚠️ В компоненте i18n входные параметры слота не поддерживаются.

# Использование синтаксиса places

Внимание!

В следующей мажорной версии входные параметры place и places будут объявлены устаревшими. Рекомендуем использовать синтаксис слотов.

Поддержка с версии

🆕 7.2+

Обратите внимание

⚠️ В компоненте i18n содержимое, состоящее только из пробелов, будет опущено.

Именованное форматирование поддерживается с помощью атрибута place. Например:

<div id="app">
+  <!-- ... -->
+  <i18n path="info" tag="p">
+    <span place="limit">{{ changeLimit }}</span>
+    <a place="action" :href="changeUrl">{{ $t('change') }}</a>
+  </i18n>
+  <!-- ... -->
+</div>
+
const messages = {
+  en: {
+    info: 'You can {action} until {limit} minutes from departure.',
+    change: 'change your flight',
+    refund: 'refund the ticket'
+  }
+}
+
+const i18n = new VueI18n({
+  locale: 'en',
+  messages
+})
+new Vue({
+  i18n,
+  data: {
+    changeUrl: '/change',
+    refundUrl: '/refund',
+    changeLimit: 15,
+    refundLimit: 30
+  }
+}).$mount('#app')
+

Результат:

<div id="app">
+  <!-- ... -->
+  <p>
+    You can <a href="/change">change your flight</a> until
+    <span>15</span> minutes from departure.
+  </p>
+  <!-- ... -->
+</div>
+

Обратите внимание

⚠️ Для использования именованного форматирования все потомки компонента i18n должны иметь установленный атрибут place. В противном случае будет использовано форматирование списком.

Если всё же необходимо интерполировать текстовое содержимое с помощью именованного форматирования, можно определить свойство places на компоненте i18n. Например:

<div id="app">
+  <!-- ... -->
+  <i18n path="info" tag="p" :places="{ limit: refundLimit }">
+    <a place="action" :href="refundUrl">{{ $t('refund') }}</a>
+  </i18n>
+  <!-- ... -->
+</div>
+

Результат:

<div id="app">
+  <!-- ... -->
+  <p>
+    You can <a href="/refund">refund your ticket</a> until 30 minutes from
+    departure.
+  </p>
+  <!-- ... -->
+</div>
+
+ + + diff --git a/ru/guide/lazy-loading.html b/ru/guide/lazy-loading.html new file mode 100644 index 000000000..55f82e3d3 --- /dev/null +++ b/ru/guide/lazy-loading.html @@ -0,0 +1,156 @@ + + + + + + Ленивая загрузка переводов | Vue I18n + + + + + + + + + +

# Ленивая загрузка переводов

Одновременная загрузка всех файлов переводов может быть излишней и ненужной.

Ленивая или асинхронная загрузка файлов переводов очень просто реализуется при использовании Webpack.

Предположим, что у нас есть каталог проекта следующей структуры:

наш-проект-отлично
+-dist
+-src
+--routes
+--store
+--setup
+---i18n-setup.js
+--lang
+---en.js
+---it.js
+

В каталоге lang располагаются все файлы переводов. В каталоге setup сгруппированы различные файлы настроек, например настройки i18n, регистрация глобальных компонентов, инициализации плагинов и другое.

// i18n-setup.js
+import Vue from 'vue'
+import VueI18n from 'vue-i18n'
+import messages from '@/lang/en'
+import axios from 'axios'
+
+Vue.use(VueI18n)
+
+export const i18n = new VueI18n({
+  locale: 'en', // установка локализации
+  fallbackLocale: 'en',
+  messages // установка сообщений локализации
+})
+
+const loadedLanguages = ['en'] // список локализаций, которые пред-загружены
+
+function setI18nLanguage(lang) {
+  i18n.locale = lang
+  axios.defaults.headers.common['Accept-Language'] = lang
+  document.querySelector('html').setAttribute('lang', lang)
+  return lang
+}
+
+export function loadLanguageAsync(lang) {
+  // Если локализация та же
+  if (i18n.locale === lang) {
+    return Promise.resolve(setI18nLanguage(lang))
+  }
+
+  // Если локализация уже была загружена
+  if (loadedLanguages.includes(lang)) {
+    return Promise.resolve(setI18nLanguage(lang))
+  }
+
+  // Если локализация ещё не была загружена
+  return import(
+    /* webpackChunkName: "lang-[request]" */ `@/i18n/messages/${lang}.js`
+  ).then(messages => {
+    i18n.setLocaleMessage(lang, messages.default)
+    loadedLanguages.push(lang)
+    return setI18nLanguage(lang)
+  })
+}
+

Для начала создаём новый экземпляр VueI18n как обычно. Затем определяем массив loadedLanguages в котором будем хранить список загруженных языков. Далее создаём функцию setI18nLanguage, которая будет переключать локализацию в экземпляре vueI18n, axios и где ещё это необходимо.

Функция loadLanguageAsync будет использоваться для изменения языка. Загрузка новых файлов осуществляется функцией import, которую предоставляет Webpack и позволяет загружать файлы динамически, а поскольку она возвращает Promise, то можем легко дождаться окончания загрузки.

Подробнее о динамических импортах можно изучить в документации Webpack (opens new window).

Использовать loadLanguageAsync очень просто. Например, в хуке beforeEach vue-router.

router.beforeEach((to, from, next) => {
+  const lang = to.params.lang
+  loadLanguageAsync(lang).then(() => next())
+})
+

Можно доработать реализацию, например добавив проверку поддерживается ли переданный lang или нет и вызывать reject чтобы отловить подобные случаи в хуке beforeEach и остановить навигацию.

+ + + diff --git a/ru/guide/locale.html b/ru/guide/locale.html new file mode 100644 index 000000000..e83e0f479 --- /dev/null +++ b/ru/guide/locale.html @@ -0,0 +1,130 @@ + + + + + + Переключение локализации | Vue I18n + + + + + + + + + +

# Переключение локализации

Обычно используют корневой экземпляр Vue в качестве точки истины, а все дочерние компоненты используют свойство locale от класса VueI18n передаваемого по ссылке.

Иногда может потребоваться динамически переключать локализацию. Для этого нужно изменить значение свойства locale экземпляра VueI18n.

const i18n = new VueI18n({
+  locale: 'ru', // устанавливаем локализацию по умолчанию
+  ...
+})
+
+// Создаём корневой экземпляр Vue
+new Vue({
+  i18n,
+  ...
+}).$mount('#app')
+
+// Переключаем на другую локализацию
+i18n.locale = 'en'
+

Каждый компонент содержит экземпляр VueI18n, ссылающийся на свойство $i18n, которое также можно использовать для переключения локализации.

Пример:

<template>
+  <div class="locale-changer">
+    <select v-model="$i18n.locale">
+      <option v-for="(lang, i) in langs" :key="`Lang${i}`" :value="lang">
+        {{ lang }}
+      </option>
+    </select>
+  </div>
+</template>
+
+<script>
+  export default {
+    name: 'locale-changer',
+    data() {
+      return { langs: ['ru', 'en'] }
+    }
+  }
+</script>
+

Обратите внимание

⚠️ Изменение локализации игнорируется компонентами с опцией sync: false.

Компонент vs. корневая область видимости

⚠️ Изменение $i18n.locale внутри компонента не приводит к изменению корневой локализации. Если вы полагаетесь на корневую локализацию, например, при использовании корневой запасной локализации, используйте $root.$i18n.locale вместо $i18n.locale.

+ + + diff --git a/ru/guide/messages.html b/ru/guide/messages.html new file mode 100644 index 000000000..9d433755d --- /dev/null +++ b/ru/guide/messages.html @@ -0,0 +1,254 @@ + + + + + + Синтаксис сообщений локализации | Vue I18n + + + + + + + + + +

# Синтаксис сообщений локализации

# Структура

Синтаксис сообщений локализации:

// Как определение Flowtype, синтаксис сообщений перевода аналогичен аннотации BNF
+type LocaleMessages = { [key: Locale]: LocaleMessageObject }
+type LocaleMessageObject = { [key: Path]: LocaleMessage }
+type LocaleMessageArray = LocaleMessage[]
+type MessageContext = {
+  list: (index: number) => mixed,
+  named: (key: string) => mixed,
+  linked: (key: string) => TranslateResult,
+  values: any,
+  path: string,
+  formatter: Formatter,
+  messages: LocaleMessages,
+  locale: Locale
+};
+type MessageFunction = (ctx: MessageContext) => string;
+type LocaleMessage = string | MessageFunction | LocaleMessageObject | LocaleMessageArray;
+type Locale = string
+type Path = string
+

Используя синтаксис выше, можно создать следующую структуру сообщений локализации:

{
+  // локализация 'ru'
+  "ru": {
+    "key1": "это сообщение 1", // обычное использование
+    "nested": {
+      // вложенное
+      "message1": "это вложенное сообщение 1"
+    },
+    "errors": [
+      // массив
+      "это сообщение кода ошибки 0",
+      {
+        // объект в массиве
+        "internal1": "это внутреннее сообщение кода ошибки 1"
+      },
+      [
+        // массив в массиве
+        "это вложенный массив ошибки 1"
+      ]
+    ]
+  },
+  // локализация 'en'
+  "en": {
+    // ...
+  }
+}
+

Для такой структуры сообщений локализации, можно переводить сообщения используя ключи:

<div id="app">
+  <!-- обычное использование -->
+  <p>{{ $t('key1') }}</p>
+  <!-- вложенное -->
+  <p>{{ $t('nested.message1') }}</p>
+  <!-- массив -->
+  <p>{{ $t('errors[0]') }}</p>
+  <!-- объект в массиве -->
+  <p>{{ $t('errors[1].internal1') }}</p>
+  <!-- массив в массиве -->
+  <p>{{ $t('errors[2][0]') }}</p>
+</div>
+

Результат:

<div id="app">
+  <!-- обычное использование -->
+  <p>это сообщение 1</p>
+  <!-- вложенное -->
+  <p>это вложенное сообщение 1</p>
+  <!-- массив -->
+  <p>это сообщение кода ошибки 0</p>
+  <!-- объект в массиве -->
+  <p>это внутреннее сообщение кода ошибки 1</p>
+  <!-- массив в массиве -->
+  <p>это вложенный массив ошибки 1</p>
+</div>
+

# Связанные сообщения локализации

Когда есть ключ с сообщением перевода, которое в точности повторяется в сообщении по другому ключу, то вместо дублирования можно поставить ссылку на него. Для этого к его содержимому нужно добавить префикс @: после которого указать полное имя ключа к сообщению перевода, включая пространство имён, к которому делаем ссылку.

Сообщения локализации:

const messages = {
+  en: {
+    message: {
+      the_world: 'the world',
+      dio: 'DIO:',
+      linked: '@:message.dio @:message.the_world !!!!'
+    }
+  }
+}
+

Шаблон:

<p>{{ $t('message.linked') }}</p>
+

Результат:

<p>DIO: the world !!!!</p>
+

# Форматирование связанных сообщений локализации

Если важен регистр символов в переводе, то можно управлять регистром связанного сообщения локализации. Связанные сообщения можно отформатировать используя модификатор @.modifier:key

Доступны следующие модификаторы:

  • upper: Форматирование в верхний регистр всех символов в связанном сообщении.
  • lower: Форматирование в нижний регистр всех символов в связанном сообщении.
  • capitalize: Форматирование заглавной первой буквы в связанном сообщении.

Сообщения локализации:

const messages = {
+  en: {
+    message: {
+      homeAddress: 'Home address',
+      missingHomeAddress: 'Please provide @.lower:message.homeAddress'
+    }
+  },
+  ru: {
+    message: {
+      homeAddress: 'Домашний адрес',
+      missingHomeAddress: 'Пожалуйста укажите @.lower:message.homeAddress'
+    }
+  }
+}
+
<label>{{ $t('message.homeAddress') }}</label>
+
+<p class="error">{{ $t('message.missingHomeAddress') }}</p>
+

Результат:

<label>Домашний адрес</label>
+
+<p class="error">Пожалуйста укажите домашний адрес</p>
+

При необходимости можно добавлять новые модификаторы или перезаписывать существующие через опцию modifiers в конструкторе VueI18n.

const i18n = new VueI18n({
+  locale: 'ru',
+  modifiers: {
+    // Добавление нового модификатора
+    snakeCase: str => str.split(' ').join('-')
+  },
+  messages: {
+    // ...
+  },
+})
+

# Группировка с помощью скобок

Ключ связанного сообщения также можно указывать в виде @:(message.foo.bar.baz), где ссылка на другой ключ перевода обрамляется в скобки ().

Подобное может потребоваться, если за ссылкой на другое сообщение @:message.something требуется поставить точку ., которая в противном случае считалась бы частью ссылки.

Сообщения локализации:

const messages = {
+  en: {
+    message: {
+      dio: 'DIO',
+      linked: "There's a reason, you lost, @:(message.dio)."
+    }
+  },
+  ru: {
+    message: {
+      dio: 'DIO',
+      linked: "Есть причина по которой ты проиграл, @:(message.dio)."
+    }
+  }
+}
+

Шаблон:

<p>{{ $t('message.linked') }}</p>
+

Результат:

<p>There's a reason, you lost, DIO.</p>
+

# Функция для сообщения

vue-i18n рекомендует использовать строки для формата списком или именованного формата в качестве сообщения локализации при переводе сообщений.

Однако бывают ситуации, когда из-за сложного синтаксиса языка, необходима полная мощь возможностей JavaScript. В таком случае, вместо строковых сообщений можно использовать функцию для сообщения.

Функция ниже просто возвращает приветствие:

const messages = {
+  en: {
+    greeting: (ctx) => 'hello!'
+  },
+  ru: {
+    greeting: (ctx) => 'привет!'
+  }
+}
+

Использовать функцию для сообщения очень просто! Необходимо просто указать ключ с помощью $t или t:

<p>{{ $t('greeting') }}</p>
+

Результат будет таким:

<p>привет!</p>
+

Используется возвращаемый результат из функции для сообщения.

# Именованный формат

vue-i18n поддерживает именованный формат для строковых сообщений. vue-i18n интерполирует значения с помощью $t или t и выводит их.

Тоже самое можно сделать и с функцией для сообщения, используя контекст сообщения:

Пример приветствия:

const messages = {
+  en: {
+    greeting: (ctx) => `hello, ${ctx.named('name')}!`
+  },
+  ru: {
+    greeting: (ctx) => `привет, ${ctx.named('name')}!`
+  }
+}
+

Шаблон:

<p>{{ $t('greeting', { name: 'DIO' }) }}</p>
+

Результат:

<p>привет, DIO!</p>
+

Контекст сообщения предоставляет доступ к функции named. Необходимо указать ключ, указываемым для $t или t, который разрешится требуемым значением.

# Формат списков

Использование формата списков аналогично именованному формату, описанному выше.

vue-i18n поддерживает формат списков для строковых сообщений. vue-i18n интерполирует значения с помощью $t или t и выводит их.

Тоже самое можно сделать и с функцией для сообщения, используя контекст сообщения:

Пример приветствия:

const messages = {
+  en: {
+    greeting: (ctx) => `hello, ${ctx.list(0)}!`
+  },
+  ru: {
+    greeting: (ctx) => `привет, ${ctx.list(0)}!`
+  }
+}
+

Шаблон:

<p>{{ $t('greeting', ['DIO']) }}</p>
+

Результат:

<p>привет, DIO!</p>
+

Контекст сообщения предоставляет доступ к функции list. Необходимо указать ключ, указываемым для $t или t, который разрешится требуемым значением.

# Ограничение

В функции для сообщения следующие возможности, которые доступны в строковом варианте, не будут доступны через контекст сообщения:

  • Связанные сообщения локализации
  • Плюрализация
+ + + diff --git a/ru/guide/number.html b/ru/guide/number.html new file mode 100644 index 000000000..7d8f2f4ea --- /dev/null +++ b/ru/guide/number.html @@ -0,0 +1,166 @@ + + + + + + Локализация чисел | Vue I18n + + + + + + + + + +

# Локализация чисел

Поддержка с версии

🆕 7.0+

Можно выполнять локализацию чисел по соответствующему формату.

Пример формата для чисел:

const numberFormats = {
+  'en-US': {
+    currency: {
+      style: 'currency',
+      currency: 'USD'
+    }
+  },
+  'ru-RU': {
+    currency: {
+      style: 'currency',
+      currency: 'RUB',
+      currencyDisplay: 'symbol'
+    }
+  }
+}
+

Как указано выше, можно задать числовые форматы (например, currency для валюты) используя опции ECMA-402 Intl.NumberFormat (opens new window).

После этого, для возможности использования данного формата в сообщениях локализации, необходимо задать опцию numberFormats конструктора VueI18n:

const i18n = new VueI18n({
+  numberFormats
+})
+
+new Vue({
+  i18n
+}).$mount('#app')
+

Шаблон:

<div id="app">
+  <p>{{ $n(100, 'currency') }}</p>
+  <p>{{ $n(100, 'currency', 'ru-RU') }}</p>
+</div>
+

Результат:

<div id="app">
+  <p>$100.00</p>
+  <p>100,00 ₽</p>
+</div>
+

# Пользовательское форматирование

Поддержка с версии

🆕 8.10+

Метод $n возвращает результат в виде строки с полностью отформатированным числом, которую можно использовать лишь целиком. В случаях, когда нужно стилизовать некоторую часть отформатированного числа (например, дробную часть), $n будет недостаточно. В таких случаях необходимо использовать функциональный компонент <i18n-n>.

При минимальном наборе свойств <i18n-n> генерирует тот же результат, что и $n обернутый в сконфигурированный DOM-элемент.

Шаблон:

<div id="app">
+  <i18n-n :value="100"></i18n-n>
+  <i18n-n :value="100" format="currency"></i18n-n>
+  <i18n-n :value="100" format="currency" locale="ru-RU"></i18n-n>
+</div>
+

Результат:

<div id="app">
+  <span>100</span>
+  <span>$100.00</span>
+  <span>100,00 ₽</span>
+</div>
+

Но по-настоящему оценить удобство компонента можно лишь тогда, когда он применяется с использованием слотов с ограниченной областью видимости (opens new window).

Допустим, есть требование выводить целую часть числа полужирным шрифтом. Реализовать это можно с помощью слота integer:

<i18n-n :value="100" format="currency">
+  <span v-slot:integer="slotProps" styles="font-weight: bold">
+    {{ slotProps.integer }}
+  </span>
+</i18n-n>
+

Результат:

<span>$<span styles="font-weight: bold">100</span>.00</span>
+

Можно использовать несколько слотов одновременно:

<i18n-n :value="1234" :format="{ key: 'currency', currency: 'EUR' }">
+  <span v-slot:currency="slotProps" styles="color: green">
+    {{ slotProps.currency }}
+  </span>
+  <span v-slot:integer="slotProps" styles="font-weight: bold">
+    {{ slotProps.integer }}
+  </span>
+  <span v-slot:group="slotProps" styles="font-weight: bold">
+    {{ slotProps.group }}
+  </span>
+  <span v-slot:fraction="slotProps" styles="font-size: small">
+    {{ slotProps.fraction }}
+  </span>
+</i18n-n>
+

(Полученный HTML ниже отформатирован для лучшей читаемости)

<span>
+  <span styles="color: green"></span>
+  <span styles="font-weight: bold">1</span>
+  <span styles="font-weight: bold">,</span>
+  <span styles="font-weight: bold">234</span>
+  <span styles="font-size: small">00</span>
+</span>
+

Определить тип корневого элемента можно указать с помощью входного параметра tag. Если входной параметр не указан, то по умолчанию будет 'span'. Также можно указать значение false, чтобы вставлять дочерние элементы без создания и оборачивания в корневой.

Полный список поддерживаемых слотов, а также другие свойства <i18n-n> можно найти на странице справочника API.

+ + + diff --git a/ru/guide/pluralization.html b/ru/guide/pluralization.html new file mode 100644 index 000000000..8bbfc6884 --- /dev/null +++ b/ru/guide/pluralization.html @@ -0,0 +1,203 @@ + + + + + + Плюрализация | Vue I18n + + + + + + + + + +

# Плюрализация

Для переводимых сообщений есть возможность использовать плюрализацию. Для этого необходимо указывать строки переводов для различных случаев через разделитель |.

В шаблоне в таких случаях необходимо использовать метод $tc() вместо $t().

Сообщения локализации:

const messages = {
+  en: {
+    car: 'car | cars',
+    apple: 'no apples | one apple | {count} apples'
+  },
+  ru: {
+    car: 'машина | машины',
+    apple: 'нет яблок | одно яблоко | {count} яблок'
+  }
+}
+

Шаблон:

<p>{{ $tc('car', 1) }}</p>
+<p>{{ $tc('car', 2) }}</p>
+
+<p>{{ $tc('apple', 0) }}</p>
+<p>{{ $tc('apple', 1) }}</p>
+<p>{{ $tc('apple', 10, { count: 10 }) }}</p>
+

Результат:

<p>машина</p>
+<p>машины</p>
+
+<p>нет яблок</p>
+<p>одно яблоко</p>
+<p>10 яблок</p>
+

# Аргумент для доступа к числу

Нет необходимости явно передавать число для плюрализации. В сообщениях локализации число доступно через именованные аргументы {count} и/или {n}. При желании их можно переопределить.

Сообщения локализации:

const messages = {
+  en: {
+    apple: 'no apples | one apple | {count} apples',
+    banana: 'no bananas | {n} banana | {n} bananas'
+  },
+  ru: {
+    apple: 'нет яблок | одно яблоко | {count} яблок',
+    banana: 'нет бананов | {n} банан | {n} бананов'
+  }
+}
+

Шаблон:

<p>{{ $tc('apple', 10, { count: 10 }) }}</p>
+<p>{{ $tc('apple', 10) }}</p>
+
+<p>{{ $tc('banana', 1, { n: 1 }) }}</p>
+<p>{{ $tc('banana', 1) }}</p>
+<p>{{ $tc('banana', 100, { n: 'слишком много' }) }}</p>
+

Результат:

<p>10 яблок</p>
+<p>10 яблок</p>
+
+<p>1 банан</p>
+<p>1 банан</p>
+<p>слишком много бананов</p>
+

# Пользовательская плюрализация

Стандартная реализация плюрализации не подходит для некоторых языков (к примеру, в славянских языках другие правила множественности).

Можно предоставить собственную реализацию, передав pluralizationRules в конструктор VueI18n.

Упрощенный пример для славянских языков (Русский, Украинский и другие):

new VueI18n({
+  // Ключ - язык, для которого будет применяться правило, в этом примере - `'ru'`
+  // Value - функция плюрализации
+  pluralizationRules: {
+    /**
+     * @param choice {number} индекс выбора, переданный в $tc: `$tc('path.to.rule', choiceIndex)`
+     * @param choicesLength {number} общее количество доступных вариантов
+     * @returns финальный индекс для выбора соответственного варианта слова
+     */
+    'ru': function(choice, choicesLength) {
+      // this === VueI18n экземпляра, так что свойство locale также существует здесь
+
+      if (choice === 0) {
+        return 0;
+      }
+
+      const teen = choice > 10 && choice < 20;
+      const endsWithOne = choice % 10 === 1;
+
+      if (choicesLength < 4) {
+        return (!teen && endsWithOne) ? 1 : 2;
+      }
+      if (!teen && endsWithOne) {
+        return 1;
+      }
+      if (!teen && choice % 10 >= 2 && choice % 10 <= 4) {
+        return 2;
+      }
+
+      return (choicesLength < 4) ? 2 : 3;
+    }
+  }
+})
+

Такая реализация позволит использовать:

const messages = {
+  ru: {
+    car: '0 машин | {n} машина | {n} машины | {n} машин',
+    banana: 'нет бананов | {n} банан | {n} банана | {n} бананов'
+  }
+}
+

Для такого формата вариантов 0 вещей | количество вещей заканчивается на 1 | количество вещей заканчивается на 2-4 | количество вещей заканчивается на 5-9, 0 и числа от 11 до 19. +P.S. Славянское множественное число - сложное явление, подробнее о нем можно прочитать здесь (opens new window).

В шаблоне, по-прежнему, необходимо использовать $tc() вместо $t():

<p>{{ $tc('car', 1) }}</p>
+<p>{{ $tc('car', 2) }}</p>
+<p>{{ $tc('car', 4) }}</p>
+<p>{{ $tc('car', 12) }}</p>
+<p>{{ $tc('car', 21) }}</p>
+
+<p>{{ $tc('banana', 0) }}</p>
+<p>{{ $tc('banana', 4) }}</p>
+<p>{{ $tc('banana', 11) }}</p>
+<p>{{ $tc('banana', 31) }}</p>
+

Результат:

<p>1 машина</p>
+<p>2 машины</p>
+<p>4 машины</p>
+<p>12 машин</p>
+<p>21 машина</p>
+
+<p>нет бананов</p>
+<p>4 банана</p>
+<p>11 бананов</p>
+<p>31 банан</p>
+

# Плюрализация по умолчанию

Если для используемой локали не предоставить правило плюрализации, по умолчанию будет использовано правило для английского языка

+ + + diff --git a/ru/guide/sfc.html b/ru/guide/sfc.html new file mode 100644 index 000000000..a39227c51 --- /dev/null +++ b/ru/guide/sfc.html @@ -0,0 +1,387 @@ + + + + + + Однофайловые компоненты | Vue I18n + + + + + + + + + +

# Однофайловые компоненты

# Базовое использование

В компоненте Vue или приложении Vue с использованием однофайловых компонентов, можно управлять сообщениями локализации с помощью пользовательского блока i18n.

Код компонента из примера использования с однофайловыми компонентами (opens new window):

<i18n>
+{
+  "en": {
+    "hello": "hello world!"
+  },
+  "ru": {
+    "hello": "Привет мир!"
+  }
+}
+</i18n>
+
+<template>
+  <div id="app">
+    <label for="locale">Язык</label>
+    <select v-model="locale">
+      <option>en</option>
+      <option>ru</option>
+    </select>
+    <p>Сообщение: {{ $t('hello') }}</p>
+  </div>
+</template>
+
+<script>
+export default {
+  name: 'app',
+  data () {
+    this.$i18n.locale = 'ru';
+    return { locale: 'ru' }
+  },
+  watch: {
+    locale (val) {
+      this.$i18n.locale = val
+    }
+  }
+}
+</script>
+

# Установка vue-i18n-loader

Требуется установить vue-loader и vue-i18n-loader чтобы использовать пользовательские блоки <i18n>. Скорее всего vue-loader (opens new window) уже используется в проекте, если уже работаете с однофайловыми компонентами, но необходимо дополнительно установить vue-i18n-loader (opens new window):

npm i --save-dev @kazupon/vue-i18n-loader
+

# Webpack

Для Webpack требуется следующая конфигурация:

Для vue-loader v15 или более поздних версий:

module.exports = {
+  // ...
+  module: {
+    rules: [
+      {
+        test: /\.vue$/,
+        loader: 'vue-loader'
+      },
+      {
+        resourceQuery: /blockType=i18n/,
+        type: 'javascript/auto',
+        loader: '@kazupon/vue-i18n-loader'
+      }
+      // ...
+    ]
+  }
+  // ...
+}
+

Для vue-loader v14:

module.exports = {
+  // ...
+  module: {
+    rules: [
+      {
+        test: /\.vue$/,
+        loader: 'vue-loader',
+        options: {
+          loaders: {
+            // необходимо указать ключ `i18n` для загрузчика `vue-i18n-loader`
+            // (https://github.com/kazupon/vue-i18n-loader)
+            i18n: '@kazupon/vue-i18n-loader'
+          }
+        }
+      }
+      // ...
+    ]
+  }
+  // ...
+}
+

# Vue CLI 3.0

Vue CLI 3.0 (opens new window) скрывает конфигурацию Webpack, поэтому для добавления поддержки тегов <i18n> в однофайловых компонентах необходимо изменить существующую конфигурацию.

Для этого нужно создать файл vue.config.js в корне проекта и добавить в него следующее:

Для vue-loader v15 или более поздних версий:

module.exports = {
+  chainWebpack: config => {
+    config.module
+      .rule('i18n')
+      .resourceQuery(/blockType=i18n/)
+      .type('javascript/auto')
+      .use('i18n')
+        .loader('@kazupon/vue-i18n-loader')
+        .end()
+  }
+}
+

Для vue-loader v14:

const merge = require('deepmerge')
+
+module.exports = {
+  chainWebpack: config => {
+    config.module
+      .rule('vue')
+      .use('vue-loader')
+      .tap(options =>
+        merge(options, {
+          loaders: {
+            i18n: '@kazupon/vue-i18n-loader'
+          }
+        })
+      )
+  }
+}
+

Не забудьте установить deepmerge (opens new window)! (npm i deepmerge -D или yarn add deepmerge -D)

Подробнее о возможностях изменения существующей конфигурации Webpack можно изучить здесь (opens new window).

# Laravel-Mix

Для Laravel-mix 4 с vue-loader v15 или более поздней версии:

// Расширяем Mix с помощью метода "i18n", который загрузит vue-i18n-loader
+mix.extend( 'i18n', new class {
+        webpackRules() {
+            return [
+                {
+                    resourceQuery: /blockType=i18n/,
+                    type:          'javascript/auto',
+                    loader:        '@kazupon/vue-i18n-loader',
+                },
+            ];
+        }
+    }(),
+);
+
+// Убедитесь что вызвали .i18n() (для загрузки загрузчика) перед .js(..., ...)
+mix.i18n()
+   .js( 'resources/js/App.js', 'public/js/app.js' )
+   ...
+

Для Laravel-mix 2 с vue-loader v14:

В Laravel-mix, начиная с версии V2.1 (opens new window), можно добавлять пользовательские правила с помощью mix.extend(). Laravel-mix уже имеет собственные правила для обработки .vue файлов. Чтобы добавить vue-i18n-loader, нужно добавить в webpack.mix.js следующее:

// Код ниже внедрит загрузчик i18n (@kazupon/vue-i18n-loader) в качестве загрузчика .vue файлов.
+mix.extend( 'i18n', function( webpackConfig, ...args ) {
+    webpackConfig.module.rules.forEach( ( module ) => {
+        // Поиск компонента "vue-loader", который обрабатывает .vue файлы.
+        if( module.loader !== 'vue-loader' ) {
+            return;
+        }
+
+        // В этом модуле добавляем vue-i18n-loader для тега i18n.
+        module.options.loaders.i18n = '@kazupon/vue-i18n-loader';
+    } );
+} );
+
+// Убедитесь что вызвали .i18n() (для загрузки загрузчика) перед .js(..., ...)
+mix.i18n()
+   .js( 'resources/assets/js/App.js', 'public/js/app.js' )
+   ...
+

# Загрузка YAML

Пользовательские блоки i18n можно указывать в формате JSON или YAML (используя функцию предварительного загрузчика vue-loader).

Пользовательский блок i18n в формате YAML:

<i18n>
+  en:
+    hello: "hello world!"
+  ru:
+    hello: "привет мир!"
+</i18n>
+

Конфигурация Webpack:

Для vue-loader v15 или более поздних версий:

// Vue CLI 3.0
+module.exports = {
+  chainWebpack: config => {
+    config.module
+      .rule('i18n')
+      .resourceQuery(/blockType=i18n/)
+      .type('javascript/auto')
+      .use('i18n')
+        .loader('@kazupon/vue-i18n-loader')
+        .end()
+      .use('yaml')
+        .loader('yaml-loader')
+        .end()
+  }
+}
+

Для vue-loader v14:

module.exports = {
+  // ...
+  module: {
+    rules: [
+      {
+        test: /\.vue$/,
+        loader: 'vue-loader',
+        options: {
+          preLoaders: {
+            i18n: 'yaml-loader'
+          },
+          loaders: {
+            i18n: '@kazupon/vue-i18n-loader'
+          }
+        }
+      }
+      // ...
+    ]
+  }
+  // ...
+}
+

# Несколько пользовательских блоков

Можно использовать сообщения локализации из нескольких пользовательских блоков i18n.

<i18n src="./common/locales.json"></i18n>
+<i18n>
+  {
+    "en": {
+      "hello": "hello world!"
+    },
+    "ru": {
+      "hello": "Привет мир!"
+    }
+  }
+</i18n>
+

В примере выше, первый пользовательский блок загружает общие сообщения локализации с помощью атрибута src, второй пользовательский блок загружает сообщения локализации, которые определены только в этом однофайловом компоненте. Все они будут объединены в качестве сообщений локализации компонента.

Несколько пользовательских блоков полезны, когда использовать их в качестве модулей.

# Локальные стили

При использовании vue-i18n с локальными стилями (style scoped) необходимо помнить и использовать глубокий селектор (opens new window) для стилизации элемента внутри строки перевода. Например:

Когда перевод содержит только текст (работает без глубокого селектора)

<i18n>
+  {
+    "en": {
+      "hello": "hello world!"
+    },
+    "ru": {
+      "hello": "Привет мир!"
+    }
+  }
+</i18n>
+
+<template>
+  <div class="parent">
+    <p>Сообщение: {{ $t('hello') }}</p>
+  </div>
+</template>
+
+<!-- Будет работать -->
+<style scoped>
+  .parent p {
+    color: #42b883;
+  }
+</style>
+

Когда перевод содержит HTML-элемент (необходимо использовать глубокий селектор)

<i18n>
+  {
+    "en": {
+      "hello": "hello<span>world!</span>"
+    },
+    "ru": {
+      "hello": "привет <span>мир!</span>"
+    }
+  }
+</i18n>
+
+<template>
+  <div class="parent">
+    <p v-html="$t('hello')"></p>
+  </div>
+</template>
+
+<!-- НЕ БУДЕТ РАБОТАТЬ! -->
+<style scoped>
+  .parent p {
+    color: #42b883;
+  }
+
+  .parent p span {
+    color: red;
+  }
+</style>
+
+<!-- Будет работать >>> -->
+<style scoped>
+  .parent p {
+    color: #42b883;
+  }
+
+  .parent p >>> span {
+    color: red;
+  }
+</style>
+
+<!-- Будет работать /deep/ -->
+<style scoped>
+  .parent p {
+    color: #42b883;
+  }
+
+  .parent p /deep/ span {
+    color: red;
+  }
+</style>
+
+<!-- Будет работать ::v-deep -->
+<style scoped>
+  .parent p {
+    color: #42b883;
+  }
+
+  ::v-deep .parent p span {
+    color: red;
+  }
+</style>
+

# Пользовательские блоки в функциональном компоненте

Если в шаблоне однофайловых компонентов используется функциональный компонент и определены пользовательские блоки i18n, то обратите внимание что невозможно локализовать с помощью сообщений локализации.

Например, следующий код не может использовать сообщения локализации из блока i18n.

<i18n>
+  {
+    "en": {
+      "hello": "hello world"
+    },
+    "ru": {
+      "hello": "привет мир"
+    }
+  }
+</i18n>
+
+<template functional>
+  <!-- Сообщение локализации 'hello' из родительского экземпляра -->
+  <p>{{ parent.$t('hello') }}</p>
+</template>
+
+ + + diff --git a/ru/guide/tooling.html b/ru/guide/tooling.html new file mode 100644 index 000000000..06bccee45 --- /dev/null +++ b/ru/guide/tooling.html @@ -0,0 +1,95 @@ + + + + + + Инструментарий | Vue I18n + + + + + + + + + +

# Инструментарий

Для поддержки i18n приложений Vue некоторые инструменты предоставляются официально.

Также есть инструменты от сторонних разработчиков, которые интегрируются в Vue I18n.

# Официальный инструментарий

# Плагин для Vue CLI

vue-cli-plugin-i18n (opens new window) — официальный плагин для Vue CLI.

С помощью этого плагина можно настроить среду i18n для приложения Vue и поддерживать среду разработки i18n.

# Модуль для Nuxt

nuxt-i18n (opens new window) — соответствующий модуль для Nuxt.js.

# Загрузчик для Webpack

vue-i18n-loader (opens new window) — официальный загрузчик для webpack.

С помощью этого загрузчика можно использовать пользовательские блоки i18n в однофайловых компонентах.

Подробнее о пользовательских блоках i18n можно изучить в разделе Однофайловых компонентов

# Плагин для ESLint

eslint-plugin-vue-i18n (opens new window) — ESLint-плагин для Vue I18n.

Позволяет легко интегрировать функции проверки локализацией в ваше приложение Vue.js.

# Расширения

vue-i18n-extensions (opens new window) — предоставляет некоторые расширения дляVue I18n.

Эти расширения позволяет использовать в рендеринге на стороне сервера (SSR) и улучшить производительность i18n.

# Сторонние разработки

# BabelEdit

BabelEdit (opens new window) — редактор переводов для веб-приложений.

BabelEdit может переводить файлы json, а также умеет работать с пользовательскими блоками i18n однофайловых компонентов.

Подробнее про BabelEdit можно узнать на странице введения (opens new window).

# i18n Ally

i18n Ally (opens new window) — расширение i18n для VSCode.

i18n Ally предоставляет потрясающий DX для разработки с использованием i18n.

Подробнее о расширении i18n Ally можно изучить в README (opens new window).

# i18nPlugin (платформа intellij)

i18nPlugin (opens new window) — плагин Intellij idea для поддержки i18next (Jetbrains plugin page (opens new window)).

Плагин для i18n typescript/javascript/PHP. Поддерживает vue-i18n. Для включения поддержки vue-i18n в настройках -> Tools -> i18n Plugin configuration выберите "Vue-i18n". Необходимо установить каталоги с файлами локализаций (по умолчанию locales).

# vue-i18n-extract

vue-i18n-extract (opens new window) выполняет статический анализ проекта Vue.js на основе vue-i18n и сообщает следующую информацию:

  • список всех неиспользуемых ключей vue-i18n (записи, найденные в файлах перевода, но не использованные в проекте)
  • список всех пропущенных ключей (записи, найденные в проекте, но отсутствующие в файлах перевода)

Имеется возможность отобразить результат в консоли или записать его в файл json.

Пропущенные ключи также могут быть автоматически добавлены в заданные файлы переводов.

+ + + diff --git a/ru/index.html b/ru/index.html new file mode 100644 index 000000000..3400b1753 --- /dev/null +++ b/ru/index.html @@ -0,0 +1,101 @@ + + + + + + Vue I18n + + + + + + + + + +
hero

+ Vue I18n +

+ Vue I18n — плагин для интернационализации во Vue.js +

+ Введение → +

🥇 Золотые спонсоры

Nuxt.js

🥈 Серебряные спонсоры

Редактор переводов BabelEdit для приложений (веб-приложений)

🥉 Бронзовые спонсоры

zenarchitects sendcloud

Простой

Позволяет легко добавить интернационализацию в приложение с помощью простого API

Функциональный

В дополнение к переводам, поддерживает плюрализацию, локализацию для чисел, дат ... и т.д.

Ориентированный на компоненты

Можно управлять сообщениями локализации в однофайловых компонентах

+ + + diff --git a/ru/installation.html b/ru/installation.html new file mode 100644 index 000000000..e8d840bb6 --- /dev/null +++ b/ru/installation.html @@ -0,0 +1,114 @@ + + + + + + Установка | Vue I18n + + + + + + + + + +

# Установка

# Примечание совместимости

  • Vue.js версии 2.0.0+

# Загрузка файла / CDN

https://unpkg.com/vue-i18n@8 (opens new window)

Сервис unpkg.com (opens new window) предоставляет CDN-ссылки на основе NPM-пакетов. Ссылка выше будет всегда указывать на последнюю версию на NPM. Можно использовать конкретную версию или тег с помощью URL следующего вида https://unpkg.com/vue-i18n@8.17.5/dist/vue-i18n.js (opens new window)

При подключении vue-i18n после Vue плагин установит себя автоматически:

<script src="https://unpkg.com/vue/dist/vue.js"></script>
+<script src="https://unpkg.com/vue-i18n@8"></script>
+

# NPM

npm install vue-i18n
+

# Yarn

yarn add vue-i18n
+

При использовании системы модулей нужно явно устанавливать vue-i18n +через Vue.use():

import Vue from 'vue'
+import VueI18n from 'vue-i18n'
+
+Vue.use(VueI18n)
+

Подобного не требуется делать при подключении через глобальный тег <script>.

# Vue CLI 3.x

vue add i18n
+

Предварительно требуется установить Vue CLI 3.x, его можно установить следующей командой:

npm install @vue/cli -g
+

# Dev-сборка

При необходимости использовать последнюю dev-сборку нужно склонировать репозиторий с GitHub и выполнить сборку vue-i18n самостоятельно.

git clone https://github.com/kazupon/vue-i18n.git node_modules/vue-i18n
+cd node_modules/vue-i18n
+npm install # или `yarn`
+npm run build  # или `yarn run build`
+

# Отличия различных сборок

Внутри каталога dist / NPM-пакета (opens new window) можно обнаружить несколько различных сборок VueI18n. Вот следующие отличия между ними:

  • UMD: vue-i18n.js
  • CommonJS: vue-i18n.common.js
  • ES Module для систем сборки: vue-i18n.esm.js
  • ES Module для браузеров: vue-i18n.esm.browser.js

# Термины

  • UMD (opens new window): UMD-сборки можно использовать непосредственно в браузере через тег <script>. Файл по умолчанию с Unpkg CDN https://unpkg.com/vue-i18n (opens new window) указывает на UMD-сборку (vue-i18n.js).

  • CommonJS (opens new window): CommonJS сборки предназначены для использования со старыми системами сборки, такими как browserify (opens new window) или webpack 1 (opens new window). Файлом по умолчанию для этих систем сборки (pkg.main) будет сборка CommonJS (vue-i18n.common.js).

  • ES Module (opens new window): VueI18n, начиная с версии 8.11, предоставляет две сборки ES-модулей (ESM):

    • ESM для систем сборки: предназначен для использования с современными системами сборки, такими как webpack 2 (opens new window) или Rollup (opens new window). Формат ESM разработан для возможности статического анализа, чтобы системы сборки могли применять "tree-shaking" и удалять неиспользуемый код из финального приложения. Файлом по умолчанию для этих систем сборки (pkg.module) будет ES-сборка (vue-i18n.esm.js).
    • ESM для браузеров (только для 8.11+, vue-i18n.esm.browser.js): предназначен для импорта напрямую в современных браузерах через тег <script type="module">.
+ + + diff --git a/ru/introduction.html b/ru/introduction.html new file mode 100644 index 000000000..292fff926 --- /dev/null +++ b/ru/introduction.html @@ -0,0 +1,95 @@ + + + + + + Введение | Vue I18n + + + + + + + + + +

# Введение

Предупреждение

⚠️ Документация для Vue I18n v6.0 или более поздних версий. Если используете и ищете документацию для версии v5.x, обратитесь к разделу устаревшей версии.

Vue I18n — плагин для интернационализации во Vue.js. Он легко интегрирует дополнительные возможности по локализации приложения Vue.js.

Изучение лучше начинать с раздела Начало работы

# Спонсоры

# 🥇 Золото

Nuxt.js

# 🥈 Серебряные

Редактор переводов BabelEdit для приложений (веб-приложений)

# 🥉 Бронза

zenarchitects sendcloud

# Поддержите на Patreon

Ваша компания для создания потрясающих приложений использует vue-i18n или vue-cli-plugin-i18n? Присоединяйтесь к другим патронам или становитесь спонсором, чтобы увидеть свой логотип в документации! Поддержка на Patreon позволяет автору меньше работать и больше заниматься развитием свободным опенсорсом, таким как vue-i18n! Спасибо!

+ + + diff --git a/ru/started.html b/ru/started.html new file mode 100644 index 000000000..99d395b8d --- /dev/null +++ b/ru/started.html @@ -0,0 +1,140 @@ + + + + + + Начало работы | Vue I18n + + + + + + + + + +

# Начало работы

ПРИМЕЧАНИЕ

В примерах кода этого руководства используется ES2015 (opens new window).

# HTML

<script src="https://unpkg.com/vue/dist/vue.js"></script>
+<script src="https://unpkg.com/vue-i18n@8"></script>
+
+<div id="app">
+  <p>{{ $t("message.hello") }}</p>
+</div>
+

# JavaScript

// При использовании модульной системы (например, через vue-cli)
+// нужно импортировать Vue и VueI18n и вызвать Vue.use(VueI18n).
+//
+// import Vue from 'vue'
+// import VueI18n from 'vue-i18n'
+//
+// Vue.use(VueI18n)
+
+// Готовые переводы сообщений локализаций
+const messages = {
+  en: {
+    message: {
+      hello: 'hello world'
+    }
+  },
+  ru: {
+    message: {
+      hello: 'Привет мир'
+    }
+  }
+}
+
+// Создание экземпляра VueI18n с настройками
+const i18n = new VueI18n({
+  locale: 'ru', // установка локализации по умолчанию
+  messages // установка сообщений локализаций
+})
+
+// Создание экземпляра Vue с опцией `i18n`
+new Vue({ i18n }).$mount('#app')
+
+// Теперь можно запускать приложение!
+

Результат будет таким:

<div id="#app">
+  <p>Привет мир</p>
+</div>
+
+ + + diff --git a/started.html b/started.html new file mode 100644 index 000000000..911cea0b6 --- /dev/null +++ b/started.html @@ -0,0 +1,152 @@ + + + + + + Getting started | Vue I18n + + + + + + + + + +

# Getting started

NOTE

We will be using ES2015 (opens new window) in the +code samples in the guide.

# HTML

<script src="https://unpkg.com/vue/dist/vue.js"></script>
+<script src="https://unpkg.com/vue-i18n@8"></script>
+
+<div id="app">
+  <p>{{ $t("message.hello") }}</p>
+</div>
+

# JavaScript

// If using a module system (e.g. via vue-cli), import Vue and VueI18n and then call Vue.use(VueI18n).
+// import Vue from 'vue'
+// import VueI18n from 'vue-i18n'
+//
+// Vue.use(VueI18n)
+
+// Ready translated locale messages
+const messages = {
+  en: {
+    message: {
+      hello: 'hello world'
+    }
+  },
+  ja: {
+    message: {
+      hello: 'こんにちは、世界'
+    }
+  }
+}
+
+// Create VueI18n instance with options
+const i18n = new VueI18n({
+  locale: 'ja', // set locale
+  messages, // set locale messages
+})
+
+
+// Create a Vue instance with `i18n` option
+new Vue({ i18n }).$mount('#app')
+
+// Now the app has started!
+

Output the following:

<div id="#app">
+  <p>こんにちは、世界</p>
+</div>
+
+ + + diff --git a/vue-i18n-logo.png b/vue-i18n-logo.png new file mode 100644 index 000000000..4fdeb1ffc Binary files /dev/null and b/vue-i18n-logo.png differ diff --git a/zh/api/index.html b/zh/api/index.html new file mode 100644 index 000000000..088dfff0c --- /dev/null +++ b/zh/api/index.html @@ -0,0 +1,138 @@ + + + + + + API参考 | Vue I18n + + + + + + + + + +

# API参考

# 扩展 Vue

# Vue 构造函数选项

# i18n

  • 类型: I18nOptions

基于组件的本地化选项

  • 请参阅: VueI18n 类构造函数选项

# Vue 注入方法

# $t

  • 参数

    • {Path} key:必填
    • {Locale} locale:可选
    • {Array | Object} values:可选
  • 返回值:TranslateResult

本地化语言环境信息 key,在本地化时组件的语言环境信息优先于全局语言环境信息。如果未指定组件的语言环境信息,就使用全局语言环境信息进行本地化。如果你指定了 locale 参数,则使用 locale 提供的语言环境进行本地化。如果你为列表/格式化的语言环境信息指定了 key,就必须同时指定 values。有关 values 的详细信息,请参阅格式化

提示

注意,你需要在生命周期方法中保证上下文是组件实例 (例如在 data 选项中,const $t = this.$t.bind(this))。

# $tc

  • 参数:

    • {Path} key:必填
    • {number} choice:可选,默认为 1
    • {Locale} locale:可选
    • {string | Array | Object} values:可选
  • 返回值:TranslateResult

以复数形式将语言环境信息 key 本地化。在本地化时组件的语言环境信息优先于全局语言环境信息。如果未指定组件的语言环境信息,就使用全局语言环境信息进行本地化。如果你指定了 locale 参数,则使用 locale 提供的语言环境进行本地化。如果将 values 指定为字符串,则该字符串会作为语言环境信息进行本地化。如果将 values 指定为 Array 或 Object,则格式必须为 $tvalues

提示

注意,你需要在生命周期方法中保证上下文是组件实例 (例如在 data 选项中,const $tc = this.$tc.bind(this))

# $te

  • 参数:

    • {Path} key:必填
    • {Locale} locale:可选
  • 返回值:boolean

检查 key 是否存在。在 Vue 实例中,如果未指定组件语言环境信息,则使用全局语言环境信息。如果指定了 locale,则使用 locale 的语言环境。

提示

注意,你需要在生命周期方法中保证上下文是组件实例 (例如在 data 选项中,const $te = this.$te.bind(this))。

# $d

🆕 7.0+ 新增

  • 参数:

    • {number | Date} value:必填
    • {Path | Object} key:可选
    • {Locale | Object} locale:可选
  • 返回值:DateTimeFormatResult

将日期时间 valuekey 的格式本地化。日期时间格式 key 需要注册到 VueI18n 类的 dateTimeFormats 选项,并依赖于 VueI18n 构造函数的 locale 选项。如果要指定 locale 参数,它将优先于 VueI18n 构造函数的 locale 选项。

如果 dateTimeFormats 选项中不存在日期时间格式的 key,则根据 VueI18n 构造函数的 fallbackLocale 选项回退。

提示

注意,你需要在生命周期方法中保证上下文是组件实例 (例如在 data 选项中,const $d = this.$d.bind(this))。

# $n

🆕 7.0+ 新增

  • 参数:

    • {number} value:必填
    • {Path | Object} key:可选
    • {Locale} locale:可选
  • 返回值:NumberFormatResult

将数字 valuekey 的格式本地化。数字格式 key 需要注册到 VueI18n 类的 numberFormats 选项,并依赖于 VueI18n 构造函数的 locale 选项。如果要指定 locale 参数,它将优先于 VueI18n 构造函数的 locale 选项。

如果 numberFormats 选项中不存在用数字格式 key,则根据 VueI18n 构造函数的 fallbackLocale 选项回退。

如果第二个 key 参数指定为对象,则它应具有以下属性:

  • key {Path}:可选,数字格式
  • locale {Locale}:可选,语言环境
  • style {string}:可选,数字格式选项
  • currency {string}:可选,数字格式选项
  • currencyDisplay {string}:可选,数字格式选项
  • useGrouping {boolean}:可选,数字格式选项
  • minimumIntegerDigits {string}:可选,数字格式选项
  • minimumFractionDigits {string}:可选,数字格式选项
  • maximumFractionDigits {string}:可选,数字格式选项
  • minimumSignificantDigits {string}:可选,数字格式选项
  • maximumSignificantDigits {string}:可选,数字格式选项
  • localeMatcher {string}:可选,数字格式选项
  • formatMatcher {string}:可选,数字格式选项

任何指定数字的格式选项将优先于 VueI18n 构造函数的 numberFormats

提示

注意,你需要在生命周期方法中保证上下文是组件实例 (例如在 data 选项中,const $n = this.$n.bind(this))。

# 注入属性

# $i18n

  • 类型:I18n

  • 只读

若已经指定了 VueI18n 实例,则将其返回。

如果在组件选项中指定了 i18n 选项,则可以在组件上获得 VueI18n 实例,否则,你将获得 VueI18n 的根实例。

# VueI18n

Vuei18n 类实现了 I18n flowtype 接口 (opens new window)

# 静态属性

# version

  • 类型:string

vue-i18n 版本

# availabilities

🆕 7.0+ 新增

  • 类型:IntlAvailability

是否提供以下国际化功能:

  • {boolean} dateTimeFormat:环境敏感的时间格式

  • {boolean} numberFormat:环境敏感的数字格式

由于使用 ECMAScript Internationalization API (ECMA-402) 实现,上述国际化功能取决于浏览器环境 (opens new window)

# 构造函数选项

你可以基于flowtype 定义 (opens new window) 中的 I18nOptions 指定下列构造函数选项

# locale

  • 类型:Locale

  • 默认值:'en-US'

语言环境。

# fallbackLocale

  • 类型:Locale

  • 默认值:'en-US'

预设的语言环境。

# messages

  • 类型:LocaleMessages

  • 默认值:{}

本地化的语言环境信息。

# dateTimeFormats

🆕 7.0+ 新增

  • 类型:DateTimeFormats

  • 默认值:{}

本地化的日期时间格式。

# numberFormats

🆕 7.0+ 新增

  • 类型:NumberFormats

  • 默认值:{}

本地化的数字格式。

# availableLocales

🆕 8.9.0+ 新增

  • 类型:Locale[]

  • 默认值:[]

  • 示例:["en", "ja"]

以词法顺序排列的 messages 中的可用语言环境列表。

# formatter

  • 类型:Formatter

  • 默认值: Built in formatter

使用 Formatter 接口实现的格式化。

# missing

  • 类型:MissingHandler

  • 默认值:null

缺少本地化时的处理函数。该处理函数在被调用时会使用本地化目标语言环境,本地化路径关键字和 Vue 实例。

如果设置了该函数,则本地化信息未定义时不会产生警告。

# fallbackRoot

  • 类型:Boolean

  • 默认值:true

在组件本地化中,当本地化失败时是否回退到根级别 (全局) 本地化。

如果为 false,则会发出警告,并返回 key。

# fallbackRootWithEmptyString

🆕 8.26+ 新增

  • Type: Boolean

  • Default: true

在组件本地化中,当本地化文本为空字符串时,是否回退到根级别 (全局) 本地化。

请注意,vue-i18n 9.x版本的默认行为是对空字符串本地化文本进行回退到根级别本地化。

如果为false,则空的本地化文本将不会回退到根目录,并将保留为空字符串。

# sync

  • 类型:Boolean

  • 默认值:true

是否将根级别语言环境与组件本地化语言环境同步。

如果为 false,则无论根级别语言环境如何,都要为每个组件语言环境进行本地化。

# silentTranslationWarn

6.1+ 新增

  • 类型:Boolean

  • 默认值:false

是否取消本地化失败时输出的警告。

如果为 true,则禁止本地化失败警告。

# silentFallbackWarn

🆕 8.8 新增

  • 类型:Boolean
  • 默认值:false

是否在回退到 fallbackLocaleroot 时取消警告。

如果为 true,则仅在根本没有可用的转换时生成警告,而不是在回退时。

# pluralizationRules

8.5+

  • Type: PluralizationRules

  • Default: {}

A set of rules for word pluralization in a following format:

  {
+    // Key - locale for the rule to be applied to.
+    // Value - mapping function that maps a choice index from `$tc` to the actual choice of the plural word. (See getChoiceIndex for details)
+    'pt': function(choice, choiceIndex) => Number/* index of the plural word */;
+    'ru': function(choice, choiceIndex) => Number/* index of the plural word */;
+    'en': function(choice, choiceIndex) => Number/* index of the plural word */;
+    'jp': function(choice, choiceIndex) => Number/* index of the plural word */;
+  }
+

# preserveDirectiveContent

8.7+ 新增

  • 类型:Boolean

  • 默认值:false

在指令解除绑定后,v-t 指令的元素是否应该保留 textContent

# Properties

# locale

  • 类型:Locale

  • 可读/可写

语言环境。

# fallbackLocale

  • 类型:Locale

  • 可读/可写

预设的语言环境。

# messages

  • 类型:LocaleMessages

  • 只读

本地化的语言环境信息。

# dateTimeFormats

🆕 7.0+ 新增

  • 类型:DateTimeFormats

  • 只读

本地化的日期时间格式。

# numberFormats

🆕 7.0+ 新增

  • 类型:NumberFormats

  • 只读

本地化的数字格式。

# missing

  • 类型:MissingHandler

  • 可读/可写

缺少本地化时的处理函数。

# formatter

  • 类型:Formatter

  • 可读/可写

使用 Formatter 接口实现的格式化。

# silentTranslationWarn

6.1 新增

  • 类型:boolean

  • 可读/可写

是否取消本地化失败时输出的警告。

# pluralizationRules

8.5+

  • Type: PluralizationRules

  • Read/Write

A set of locale-dependent rules for word pluralization.

# preserveDirectiveContent

8.7+ 新增

  • 类型:boolean

  • 可读/可写

在指令解除绑定后,v-t 指令的元素是否应该保留 textContent

# 方法

# getChoiceIndex

  • 参数:

    • {number} choice
    • {number} choicesLength
  • 返回值:finalChoice {number}

根据当前的数字和一组给定的选项,获取其复数索引,可以通过原型变更覆盖:

VueI18n.prototype.getChoiceIndex = /* 自定义实现 */
+

However, for most usages pluralizationRules constructor option should be enough.

# getLocaleMessage( locale )

  • 参数:

    • {Locale} locale
  • 返回值:LocaleMessageObject

获取语言环境的 locale 信息。

# setLocaleMessage( locale, message )

  • 参数:

    • {Locale} locale
    • {LocaleMessageObject} message

设置语言环境的 locale 信息。

# mergeLocaleMessage( locale, message )

6.1+ 新增

  • 参数:

    • {Locale} locale
    • {LocaleMessageObject} message

将语言环境信息 locale 合并到已注册的语言环境信息中。

# t( key, [locale], [values] )

  • 参数:

    • {Path} key:必填
    • {Locale} locale:可选
    • {Array | Object} values:可选
  • 返回值:TranslateResult

这与 $t 方法返回的 Function 相同。更多细节见$t

# tc( key, [choice], [values] )

  • 参数:

    • {Path} key:必填
    • {number} choice:可选,默认为 1
    • {string | Array | Object} values:可选
  • 返回值:TranslateResult

这与 $tc 方法返回的 Function 相同。更多细节见$tc

# te( key, [locale] )

  • 参数:

    • {string} key:必填
    • {Locale} locale:可选
  • 返回值:boolean

检查全局语言环境信息中是否存在键名路径。如果指定了 locale,请检查语言环境信息 locale

# getDateTimeFormat ( locale )

🆕 7.0+ 新增

  • 参数:

    • {Locale} locale
  • 返回值:DateTimeFormat

获取语言环境的日期时间格式。

# setDateTimeFormat ( locale, format )

🆕 7.0+ 新增

  • 参数:

    • {Locale} locale
    • {DateTimeFormat} format

设置语言环境的日期时间格式。

# mergeDateTimeFormat ( locale, format )

🆕 7.0+ 新增

  • 参数:

    • {Locale} locale
    • {DateTimeFormat} format

将已注册的日期时间格式与语言环境的日期时间格式合并。

# d( value, [key], [locale] )

🆕 7.0+ 新增

  • 参数:

    • {number | Date} value:必填
    • {Path | Object} key:可选
    • {Locale | Object} locale:可选
  • 返回值:DateTimeFormatResult

这与 Vue 实例方法的 $d 方法相同。更多细节见$d

# getNumberFormat ( locale )

🆕 7.0+ 新增

  • 参数:

    • {Locale} locale
  • 返回值:NumberFormat

获取语言环境的数字格式。

# setNumberFormat ( locale, format )

🆕 7.0+ 新增

  • 参数:

    • {Locale} locale
    • {NumberFormat} format

设置语言环境的数字格式。

# mergeNumberFormat ( locale, format )

🆕 7.0+ 新增

  • 参数:

    • {Locale} locale
    • {NumberFormat} format

将已注册的数字格式与语言环境的数字格式合并。

# n( value, [key], [locale] )

🆕 7.0+ 新增

  • 参数:

    • {number} value:必填
    • {Path | Object} key:可选
    • {Locale} locale:可选
  • 返回值:NumberFormatResult

这与 Vue 实例方法的 $n 方法相同。更多细节见$n

# 指令

🆕 7.3+ 新增

# v-t

  • 预期:string | Object

  • 修饰符:

    • .preserve:(8.7.0 新增) 当指令解除绑定时,保留元素 textContent
  • 详细:

更新使用语言环境信息进行本地化的元素 textContent。你可以使用字符串语法或对象语法。字符串语法可以指定为语言环境信息的关键字路径。如果可以使用对象语法,则需要将以下参数指定为对象键:

  • path:必填,语言环境信息的关键字
  • locale:可选,语言环境
  • args:可选,用于列表或命名格式

注意

v-t 指令解除绑定时,默认情况下将清除元素 textContent。在过渡动画 (opens new window)内部使用的时候,可能出现不合预期的情况。为了在指令解除绑定之后保留 textContent 数据,可使用 .preserve 修饰符或全局的 preserveDirectiveContent 选项

  • 示例:
<!-- 字符串语法:字面量 -->
+<p v-t="'foo.bar'"></p>
+
+<!-- 字符串语法:通过数据或计算属性绑定 -->
+<p v-t="msg"></p>
+
+<!-- 对象语法: 字面量 -->
+<p v-t="{ path: 'hi', locale: 'ja', args: { name: 'kazupon' } }"></p>
+
+<!-- 对象语法: 通过数据或计算属性绑定 -->
+<p v-t="{ path: greeting, args: { name: fullName } }"></p>
+
+<!-- `preserve` 修饰符 -->
+<p v-t.preserve="'foo.bar'"></p>
+

# 组件

# i18n 函数式组件

🆕 7.0+ 新增

# 参数:

  • path {Path}:必填,关于语言环境信息的键名路径
  • locale {Locale}:可选,语言环境
  • tag {string}:可选,默认值 span
  • places {Array | Object}:可选 (7.2 新增)

# 用法:

<div id="app">
+  <!-- ... -->
+  <i18n path="term" tag="label" for="tos">
+    <a :href="url" target="_blank">{{ $t('tos') }}</a>
+  </i18n>
+  <!-- ... -->
+</div>
+
const messages = {
+  en: {
+    tos: 'Term of Service',
+    term: 'I accept xxx {0}.'
+  },
+  ja: {
+    tos: '利用規約',
+    term: '私は xxx の{0}に同意します。'
+  }
+}
+
+const i18n = new VueI18n({
+  locale: 'en',
+  messages
+})
+new Vue({
+  i18n,
+  data: {
+    url: '/term'
+  }
+}).$mount('#app')
+

# 请参阅:

组件插值

# 特殊属性

# place

🆕 7.2+ 新增

# 预期:{number | string}

用于组件插槽,指示格式列表的索引值或具名格式的关键字。

有关详细用法,请参阅下面链接的指南部分。

# 请参阅:

组件插值

+ + + diff --git a/zh/guide/component.html b/zh/guide/component.html new file mode 100644 index 000000000..ff404578e --- /dev/null +++ b/zh/guide/component.html @@ -0,0 +1,190 @@ + + + + + + 基于组件的本地化 | Vue I18n + + + + + + + + + +

# 基于组件的本地化

通常语言环境信息 (例如:localemessages 等) 会被设置为 VueI18n 实例的构造函数选项,并且该实例会被作为 i18n 选项设置在 Vue 的根实例上。

因此你可以全局地在 Vue 的根实例以及任何被组合的组件中使用 $t 或者 $tc 进行翻译。当然面向 Vue 组件的设计,你也可以更方便的分别控制每个组件的语言环境信息。

基于组件的本地化示例:

// 为 Vue 的根实例设置语言环境信息
+const i18n = new VueI18n({
+  locale: 'ja',
+  messages: {
+    en: {
+      message: {
+        hello: 'hello world',
+        greeting: 'good morning'
+      }
+    },
+    ja: {
+      message: {
+        hello: 'こんにちは、世界',
+        greeting: 'おはようございます'
+      }
+    }
+  }
+})
+
+// 定义组件
+const Component1 = {
+  template: `
+    <div class="container">
+     <p>Component1 locale messages: {{ $t("message.hello") }}</p>
+     <p>Fallback global locale messages: {{ $t("message.greeting") }}</p>
+   </div>`,
+  i18n: { // `i18n` 选项,为组件设置语言环境信息
+    messages: {
+      en: { message: { hello: 'hello component1' } },
+      ja: { message: { hello: 'こんにちは、component1' } }
+    }
+  }
+}
+
+new Vue({
+  i18n,
+  components: {
+    Component1
+  }
+}).$mount('#app')
+

模板:

<div id="app">
+  <p>{{ $t("message.hello") }}</p>
+  <component1></component1>
+</div>
+

输出如下:

<div id="app">
+  <p>こんにちは、世界</p>
+  <div class="container">
+    <p>Component1 locale messages: こんにちは、component1</p>
+    <p>Fallback global locale messages: おはようございます</p>
+  </div>
+</div>
+

在上面的例子中,如果组件没有语言环境信息,它将回退到全局定义的本地化信息。组件使用根实例中设置的语言 (在上面的例子中:locale: 'ja')。

注意,在默认情况下,回退到根语言环境会在控制台中生成两个警告:

[vue-i18n] Value of key 'message.greeting' is not a string!
+[vue-i18n] Fall back to translate the keypath 'message.greeting' with root locale.
+

为避免以上警告 (同时保留那些完全没有翻译给定关键字的警告) 需初始化 VueI18n 实例时设置 silentFallbackWarn:true

如果你希望在组件语言环境中进行本地化,可以在 i18n 选项中用 sync: falselocale

# 组件的共享语言环境消息

有时您可能想为某些组件导入共享的语言环境消息,而不是从全局语言环境消息(例如,组件某些功能的常用消息)回退。

您可以使用 i18nsharedMessages 选项。

通用语言环境消息示例:

export default {
+  en: {
+    buttons: {
+      save: "Save",
+      // ...
+    }
+  },
+  ja: {
+    buttons: {
+      save: "保存",
+      // ...
+    }
+  }
+}
+

Components:

import commonMessage from './locales/common' // 导入通用语言环境消息
+
+export default {
+  name: 'ServiceModal',
+  template: `
+    <div class="modal">
+      <div class="body">
+        <p>This is good service</p>
+      </div>
+      <div class="footer">
+        <button type="button">
+          {{ $t('buttons.save') }}
+        </button>
+      </div>
+    </div>
+  `,
+  i18n: {
+    messages: { ... },
+    sharedMessages: commonMessages
+  }
+}
+

如果将 sharedMessages 选项与 messages 选项一起指定,则这些消息将被合并为语言环境消息,并进入目标组件的VueI18n实例。

# 函数式组件的翻译

使用函数式组件时,所有数据 (包括 prop、子内容、插槽、父级内容等) 都通过包含属性的 context 传递,并且它无法识别 this 的范围,因此在函数式组件上使用 vue-i18n 时,你必须将 $t 称为 parent.$t,请查看以下示例:

...
+<div>
+  <a href="#" target="_blank" rel="noopener noreferrer">
+    <img src="./assets/example.jpg" :alt="parent.$t('message.hello')">
+  </a>
+</div>
+...
+
+ + + diff --git a/zh/guide/datetime.html b/zh/guide/datetime.html new file mode 100644 index 000000000..79a93c621 --- /dev/null +++ b/zh/guide/datetime.html @@ -0,0 +1,143 @@ + + + + + + 日期时间本地化 | Vue I18n + + + + + + + + + +

# 日期时间本地化

支持版本

🆕 7.0+ 新增

你可以使用你定义的格式来本地化日期时间。

日期时间格式如下:

const dateTimeFormats = {
+  'en-US': {
+    short: {
+      year: 'numeric',
+      month: 'short',
+      day: 'numeric'
+    },
+    long: {
+      year: 'numeric',
+      month: 'long',
+      day: 'numeric',
+      weekday: 'long',
+      hour: 'numeric',
+      minute: 'numeric'
+    }
+  },
+  'ja-JP': {
+    short: {
+      year: 'numeric',
+      month: 'short',
+      day: 'numeric'
+    },
+    long: {
+      year: 'numeric',
+      month: 'long',
+      day: 'numeric',
+      weekday: 'long',
+      hour: 'numeric',
+      minute: 'numeric',
+      hour12: true
+    }
+  }
+}
+

如上,你可以定义具名的 (例如:shortlong 等) 日期时间格式,并需要使用 ECMA-402 Intl.DateTimeFormat 的选项 (opens new window)

之后就像语言环境信息一样,你需要指定 VueI18n 构造函数的 dateTimeFormats 选项:

const i18n = new VueI18n({
+  dateTimeFormats
+})
+
+new Vue({
+  i18n
+}).$mount('#app')
+

模板如下:

<div id="app">
+  <p>{{ $d(new Date(), 'short') }}</p>
+  <p>{{ $d(new Date(), 'long', 'ja-JP') }}</p>
+</div>
+

输出如下:

<div id="app">
+  <p>Jan 18, 2021</p>
+  <p>2021年1月18日日曜日 午前5:47</p>
+</div>
+
+ + + diff --git a/zh/guide/directive.html b/zh/guide/directive.html new file mode 100644 index 000000000..a0732d085 --- /dev/null +++ b/zh/guide/directive.html @@ -0,0 +1,169 @@ + + + + + + 自定义指令本地化 | Vue I18n + + + + + + + + + +

# 自定义指令本地化

支持的版本

🆕 7.3+ 新增

你不仅可以使用 $t 方法进行翻译,还可以使用 v-t 自定义指令。

# 字符串语法

你可以使用字符串语法传递语言环境信息的键名路径。

JavaScript:

new Vue({
+  i18n: new VueI18n({
+    locale: 'en',
+    messages: {
+      en: { hello: 'hi there!' },
+      ja: { hello: 'こんにちは!' }
+    }
+  }),
+  data: { path: 'hello' }
+}).$mount('#string-syntax')
+

模板:

<div id="string-syntax">
+  <!-- 字符串 -->
+  <p v-t="'hello'"></p>
+  <!-- 通过数据进行键名路径绑定 -->
+  <p v-t="path"></p>
+</div>
+

输出:

<div id="string-syntax">
+  <p>hi there!</p>
+  <p>hi there!</p>
+</div>
+

# 对象语法

你可以使用对象语法。

Javascript:

new Vue({
+  i18n: new VueI18n({
+    locale: 'en',
+    messages: {
+      en: { hello: 'hi {name}!' },
+      ja: { hello: 'こんにちは、{name}!' }
+    }
+  }),
+  computed: {
+    nickName () { return 'kazupon' }
+  },
+  data: { path: 'hello' }
+}).$mount('#object-syntax')
+

模板:

<div id="object-syntax">
+  <!-- 文字 -->
+  <p v-t="{ path: 'hello', locale: 'ja', args: { name: 'kazupon' } }"></p>
+  <!-- 通过 `data` 绑定数据 -->
+  <p v-t="{ path: path, args: { name: nickName } }"></p>
+</div>
+

输出:

<div id="object-syntax">
+  <p>こんにちは、kazupon!</p>
+  <p>hi kazupon!</p>
+</div>
+

# 使用翻译

支持版本

🆕 8.7+ 新增

v-t 指令应用于 <transition> 组件 (opens new window)内的元素时,你可能会注意到过渡动画之后的翻译过的信息会消失。这与 <transition> 组件实现的方式有关——在过渡开始之前<transition> 组件内消失元素中的所有指令都将被销毁。此行为可能导致内容在短过渡时闪烁,但在长过渡时最明显。

为了确保在转换期间指令内容不会被触及,只需将.preserve 修饰符添加到 v-t 指令定义中。

Javascript:

new Vue({
+  i18n: new VueI18n({
+    locale: 'en',
+    messages: {
+      en: { preserve: 'with preserve' },
+    }
+  }),
+  data: { toggle: true }
+}).$mount('#in-transitions')
+

模板:

<div id="in-transitions">
+  <transition name="fade">
+    <span v-if="toggle" v-t.preserve="'preserve'"></span>
+  </transition>
+  <button @click="toggle = !toggle">Toggle</button>
+</div>
+

也可以在 VueI18n 实例本身设置全局设置,这将对没有修饰符的所有 v-t 指令产生影响。

Javascript:

new Vue({
+  i18n: new VueI18n({
+    locale: 'en',
+    messages: {
+      en: { preserve: 'with preserve' },
+    },
+    preserveDirectiveContent: true
+  }),
+  data: { toggle: true }
+}).$mount('#in-transitions')
+

模板:

<div id="in-transitions">
+  <transition name="fade">
+    <span v-if="toggle" v-t="'preserve'"></span>
+  </transition>
+  <button @click="toggle = !toggle">Toggle</button>
+</div>
+

关于上面的例子,请参阅示例 (opens new window)

# $t vs v-t

# $t

$t 是扩展的 Vue 实例方法, 它有以下优点和缺点:

# 优点

你可以灵活地在模板以及 Vue 实例的计算属性和方法中使用 mustash 语法 {{}}

# 缺点

$t每次重新渲染时都会被执行,因此它确实有翻译成本。

# v-t

v-t 是一个自定义指令,它有以下优点和缺点:

# 优点

v-t$t 方法具有更好的性能,因为在一次翻译时自定义指令会进行缓存。此外可以使用由 vue-i18n-extensions (opens new window) 提供的 Vue 编译器模块进行预翻译。

因此,可以进行更多性能优化

# 缺点

v-t 不能像 $t 一样灵活使用,它更复杂。带有 v-t 的翻译内容会被插入到元素的 textContent 中。此外,当你使用服务器渲染时,你需要设置自定义指令 (opens new window)createRenderer 函数的 directives 选项。

+ + + diff --git a/zh/guide/fallback.html b/zh/guide/fallback.html new file mode 100644 index 000000000..ab75d8b28 --- /dev/null +++ b/zh/guide/fallback.html @@ -0,0 +1,134 @@ + + + + + + 回退本地化 | Vue I18n + + + + + + + + + +

# 回退本地化

总结:使用fallbackLocale:'<lang>'选择首选语言缺少翻译时要使用的语言。

# 使用语言环境的隐式回退

如果给出的 locale 包含领土和可选的方言,则隐式回退将自动激活。

例如,对于 de-DE-bavarian,以下内容将被视为备用:

  1. de-DE-Bavarian
  2. de-DE
  3. de

要禁止自动回退,请添加后缀感叹号 !,例如 de-DE!

# 具有一个语言环境的显式回退

以下语言环境信息的 ja 语言环境中不存在 message 键:

const messages = {
+  en: {
+    message: 'hello world'
+  },
+  ja: {
+    // 没有翻译的本地化 `hello`
+  }
+}
+

当为 VueI18n 构造函数选项指定 fallbackLocale 选项时,message 键使用 en 语言环境进行本地化:

const i18n = new VueI18n({
+  locale: 'ja',
+  fallbackLocale: 'en',
+  messages
+})
+

模板如下:

<p>{{ $t('message') }}</p>
+

输出如下:

<p>hello world</p>
+

注意,默认情况下回退到 fallbackLocale 会产生两个控制台警告:

[vue-i18n] Value of key 'message' is not a string!
+[vue-i18n] Fall back to translate the keypath 'message' with 'en' locale.
+

为了避免这些警告 (同时保留那些完全没有翻译给定关键字的警告),需初始化 VueI18n 实例时设置 silentFallbackWarn:true

# 回退插值

由于翻译的键值是字符串,因此也可以作为翻译的值:

const messages = {
+  ja: {
+    'Hello world': 'こんにちは、世界'
+  }
+}
+

这是一种很自然的书写方式,如果在message中找不到相应的键值将回退到原本的语言:

注意: fallbackRoot的优先级高于formatFallbackMessages

<p>{{ $t('Hello world') }}</p>
+

为了实现此功能,可以通过设置formatFallbackMessagestrue

const messages = {
+  ru: {
+    'Hello {name}': 'Здравствуйте {name}'
+  }
+}
+
+const i18n = new VueI18n({
+  locale: 'ru',
+  fallbackLocale: 'en',
+  formatFallbackMessages: true,
+  messages
+})
+

模板如下:

<p>{{ $t('Hello {name}', { name: 'John' }}) }}</p>
+<p>{{ $t('The weather today is {condition}!', { condition: 'sunny' }) }}</p>
+

将会输出:

<p>Здравствуйте John</p>
+<p>The weather today is sunny!</p>
+
+ + + diff --git a/zh/guide/formatting.html b/zh/guide/formatting.html new file mode 100644 index 000000000..3b870a26d --- /dev/null +++ b/zh/guide/formatting.html @@ -0,0 +1,192 @@ + + + + + + 格式化 | Vue I18n + + + + + + + + + +

# 格式化

# 具名格式

语言环境信息如下:

const messages = {
+  en: {
+    message: {
+      hello: '{msg} world'
+    }
+  }
+}
+

模板如下:

<p>{{ $t('message.hello', { msg: 'hello' }) }}</p>
+

输出如下:

<p>hello world</p>
+

# 列表格式

语言环境信息如下:

const messages = {
+  en: {
+    message: {
+      hello: '{0} world'
+    }
+  }
+}
+

模板如下:

<p>{{ $t('message.hello', ['hello']) }}</p>
+

输出如下:

<p>hello world</p>
+

列表格式也接受类似数组的对象:

<p>{{ $t('message.hello', {'0': 'hello'}) }}</p>
+

输出如下:

<p>hello world</p>
+

# HTML 格式化

提示

⚠️ 在你的网站上动态插入任意 HTML 可能非常危险,因为它很容易导致 XSS 攻击。仅对可信内容使用 HTML 插值,而不对用户提供的内容使用。

我们建议使用组件插值 功能。

在某些情况下,你可能希望将翻译呈现为 HTML 信息而不是静态字符串。

const messages = {
+  en: {
+    message: {
+      hello: 'hello <br> world'
+    }
+  }
+}
+

模板如下:

<p v-html="$t('message.hello')"></p>
+

输出如下 (取代预先格式化的信息)

<p>hello
+<!--<br> 存在,但呈现为 html 而不是字符串-->
+world</p>
+

# 支持 ruby on rails 的 i18n 格式

语言环境信息如下:

const messages = {
+  en: {
+    message: {
+      hello: '%{msg} world'
+    }
+  }
+}
+

模板如下:

<p>{{ $t('message.hello', { msg: 'hello' }) }}</p>
+

输出如下:

<p>hello world</p>
+

# 自定义格式

有时,你可能需要使用自定义格式进行翻译 (例如:ICU 信息语法 (opens new window))。

你可以使用实现格式化接口 (opens new window) 的自定义格式化函数来实现。

以下使用 ES2015 class 语法的自定义格式化函数:

// 实现自定义格式
+class CustomFormatter {
+     constructor (options) {
+       // ...
+     }
+
+     //
+     // 插值
+     //
+     // @param {string} 信息
+     //   列表或具名格式的字符串。
+     //   例如:
+     //   - 具名格式:'Hi {name}'
+     //   - 列表格式:'Hi {0}'
+     //
+     // @param {Object | Array} 值
+     //   `message` 插值的值
+     //   使用 `$t`, `$tc` 和 `i18n` 函数式组件传递值。
+     //   e.g.
+     //   - $t('hello', { name: 'kazupon' }) -> 传递值:Object `{ name: 'kazupon' }`
+     //   - $t('hello', ['kazupon']) -> 传递值:Array `['kazupon']`
+     //   - `i18n` 函数式组件 (组件插值)
+     //     <i18n path="hello">
+     //       <p>kazupon</p>
+     //       <p>how are you?</p>
+     //     </i18n>
+     //     -> 传递值:Array (included VNode):
+     //        `[VNode{ tag: 'p', text: 'kazupon', ...}, VNode{ tag: 'p', text: 'how are you?', ...}]`
+     //
+     // @return {Array<any>}
+     //   插值,你需要返回以下内容:
+     //   - 当使用 `$t` 或 `$tc` 数组中应该是字符串。
+     //   - 当使用 `i18n` 函数式组件时 数组中应包含 VNode 对象。
+     //
+     interpolate (message, values) {
+       // 在这里实现插值逻辑
+       // ...
+
+       // 返回插值数组
+       return ['resolved message string']
+     }
+}
+
+// 注册 `formatter` 选项
+const i18n = new VueI18n({
+  locale: 'en-US',
+  formatter: new CustomFormatter(/* 这里是构造函数选项 */),
+  messages: {
+    'en-US': {
+      // ...
+    },
+    // ...
+  }
+})
+
+// 启动!
+new Vue({ i18n }).$mount('#app')
+

你可以查看自定义格式化函数的官方示例 (opens new window)

+ + + diff --git a/zh/guide/hot-reload.html b/zh/guide/hot-reload.html new file mode 100644 index 000000000..d8ad626f7 --- /dev/null +++ b/zh/guide/hot-reload.html @@ -0,0 +1,178 @@ + + + + + + 热重载 | Vue I18n + + + + + + + + + +

# 热重载

您可以使用Webpack的 Hot Module Replacement (opens new window) (HMR) 功能来监视本地化文件中的更改以及将热更改重新加载到您的应用程序中。

你可以监视本地化文件中的更改,并将更改热重载到应用程序中。

# 基本例子

如果仅使用静态语言环境集,则可以显式热加载这些语言环境:

import Vue from "vue"
+import VueI18n from "vue-i18n"
+import en from './en'
+import ja from './ja'
+
+// 语言环境信息
+const messages = {
+  en,
+  ja
+}
+
+// VueI18n 实例
+const i18n = new VueI18n({
+  locale: 'en',
+  messages
+})
+
+// 运行程序
+const app = new Vue({
+  i18n,
+  // ...
+}).$mount('#app')
+
+// 热更新
+if (module.hot) {
+  module.hot.accept(['./en', './ja'], function () {
+    i18n.setLocaleMessage('en', require('./en').default)
+    i18n.setLocaleMessage('ja', require('./ja').default)
+    // 同样可以通过 $i18n 属性进行热更新
+    // app.$i18n.setLocaleMessage('en', require('./en').default)
+    // app.$i18n.setLocaleMessage('ja', require('./ja').default)
+  })
+}
+

# 进阶范例

如果您想支持一组不断变化的语言环境,则可以使用 require.context 动态地重新加载这些语言环境:

import Vue from "vue";
+import VueI18n from "vue-i18n";
+
+Vue.use(VueI18n);
+
+// 加载所有语言环境并记住上下文
+function loadMessages() {
+  const context = require.context("./locales", true, /[a-z0-9-_]+\.json$/i);
+
+  const messages = context
+    .keys()
+    .map((key) => ({ key, locale: key.match(/[a-z0-9-_]+/i)[0] }))
+    .reduce(
+      (messages, { key, locale }) => ({
+        ...messages,
+        [locale]: context(key),
+      }),
+      {}
+    );
+
+  return { context, messages };
+}
+
+const { context, messages } = loadMessages();
+
+// VueI18n 实例
+const i18n = new VueI18n({
+  locale: "en",
+  messages,
+});
+
+// 运行程序
+const app = new Vue({
+  i18n,
+  // ...
+}).$mount('#app');
+
+// 热更新
+if (module.hot) {
+  module.hot.accept(context.id, () => {
+    const { messages: newMessages } = loadMessages();
+
+    Object.keys(newMessages)
+      .filter((locale) => messages[locale] !== newMessages[locale])
+      .forEach((locale) => {
+        messages[locale] = newMessages[locale];
+        i18n.setLocaleMessage(locale, messages[locale]);
+      });
+  });
+}
+
+ + + diff --git a/zh/guide/interpolation.html b/zh/guide/interpolation.html new file mode 100644 index 000000000..81a38c83d --- /dev/null +++ b/zh/guide/interpolation.html @@ -0,0 +1,191 @@ + + + + + + 组件插值 | Vue I18n + + + + + + + + + +

# 组件插值

# 基本用法

支持版本

🆕 7.0+ 新增

有时,我们需要使用包含 HTML 标签或组件的语言环境信息进行本地化。例如:

<p>I accept xxx <a href="/term">Terms of Service Agreement</a></p>
+

在上面的信息中,如果你使用 $t,可能你会尝试编写以下语言环境信息:

const messages = {
+  en: {
+    term1: 'I Accept xxx\'s',
+    term2: 'Terms of Service Agreement'
+  }
+}
+

你可能会尝试在以下模板中实现:

<p>{{ $t('term1') }}<a href="/term">{{ $t('term2') }}</a></p>
+

输出:

<p>I accept xxx <a href="/term">Terms of Service Agreement</a></p>
+

这是非常麻烦的,如果在语言环境信息中配置 <a> 标签,则可能由于使用了 v-html="$t('term')" 进行本地化而存在被 XSS 攻击的可能性。

你可以使用 i18n 函数式组件来避免它。例如:

<div id="app">
+  <!-- ... -->
+  <i18n path="term" tag="label" for="tos">
+    <a :href="url" target="_blank">{{ $t('tos') }}</a>
+  </i18n>
+  <!-- ... -->
+</div>
+
const messages = {
+  en: {
+    tos: 'Term of Service',
+    term: 'I accept xxx {0}.'
+  },
+  ja: {
+    tos: '利用規約',
+    term: '私は xxx の{0}に同意します。'
+  }
+}
+
+const i18n = new VueI18n({
+  locale: 'en',
+  messages
+})
+new Vue({
+  i18n,
+  data: {
+    url: '/term'
+  }
+}).$mount('#app')
+

输出如下:

<div id="app">
+  <!-- ... -->
+  <label for="tos">
+    I accept xxx <a href="/term" target="_blank">Term of Service</a>.
+  </label>
+  <!-- ... -->
+</div>
+

关于上面的例子,见示例 (opens new window)

i18n 函数式组件的子元素用 path 属性的语言环境信息进行插值。

在上面的例子中:

<a :href="url" target="_blank">{{ $t('tos') }}</a>

被插入了语言环境信息 term

在上面的示例中,组件插值遵循列表格式i18n 函数式组件的子项按其出现顺序进行插值。

# 高级用法

:::危险提示!! +在下一个主要版本中,placeplaces 属性将被弃用。 请切换到插槽语法。 +:::

支持版本

🆕 7.2+ 新增

提示

⚠️ 在 i18n 组件中,仅包含空格的文本内容将被省略。

place 特性的帮助下支持具名格式。例如:

<div id="app">
+  <!-- ... -->
+  <i18n path="info" tag="p">
+    <span place="limit">{{ changeLimit }}</span>
+    <a place="action" :href="changeUrl">{{ $t('change') }}</a>
+  </i18n>
+  <!-- ... -->
+</div>
+
const messages = {
+  en: {
+    info: 'You can {action} until {limit} minutes from departure.',
+    change: 'change your flight',
+    refund: 'refund the ticket'
+  }
+}
+
+const i18n = new VueI18n({
+  locale: 'en',
+  messages
+})
+new Vue({
+  i18n,
+  data: {
+    changeUrl: '/change',
+    refundUrl: '/refund',
+    changeLimit: 15,
+    refundLimit: 30
+  }
+}).$mount('#app')
+

输出:

<div id="app">
+  <!-- ... -->
+  <p>
+    You can <a href="/change">change your flight</a> until <span>15</span> minutes from departure.
+  </p>
+  <!-- ... -->
+</div>
+

提示

⚠️ i18n 组件的所有子项都必须设置 place 属性。否则它将回退到列表格式。

如果你仍想在命名格式中插入文本内容,可以在 i18n 组件上定义 places 属性。例如:

<div id="app">
+  <!-- ... -->
+  <i18n path="info" tag="p" :places="{ limit: refundLimit }">
+    <a place="action" :href="refundUrl">{{ $t('refund') }}</a>
+  </i18n>
+  <!-- ... -->
+</div>
+

输出:

<div id="app">
+  <!-- ... -->
+  <p>
+    You can <a href="/refund">refund your ticket</a> until 30 minutes from departure.
+  </p>
+  <!-- ... -->
+</div>
+
+ + + diff --git a/zh/guide/lazy-loading.html b/zh/guide/lazy-loading.html new file mode 100644 index 000000000..5aafdcfa2 --- /dev/null +++ b/zh/guide/lazy-loading.html @@ -0,0 +1,152 @@ + + + + + + 延迟加载翻译 | Vue I18n + + + + + + + + + +

# 延迟加载翻译

一次加载所有翻译文件是过度和不必要的。

使用 Webpack 时,延迟加载或异步加载转换文件非常简单。

让我们假设我们有一个类似于下面的项目目录

our-cool-project
+-dist
+-src
+--routes
+--store
+--setup
+---i18n-setup.js
+--lang
+---en.js
+---it.js
+

lang 文件夹是我们所有翻译文件所在的位置。setup 文件夹是我们的任意设置的文件,如 i18n-setup,全局组件 inits,插件 inits 和其他位置。

//i18n-setup.js
+import Vue from 'vue'
+import VueI18n from 'vue-i18n'
+import messages from '@/lang/en'
+import axios from 'axios'
+
+Vue.use(VueI18n)
+
+export const i18n = new VueI18n({
+  locale: 'en', // 设置语言环境
+  fallbackLocale: 'en',
+  messages // 设置语言环境信息
+})
+
+const loadedLanguages = ['en'] // 我们的预装默认语言
+
+function setI18nLanguage (lang) {
+  i18n.locale = lang
+  axios.defaults.headers.common['Accept-Language'] = lang
+  document.querySelector('html').setAttribute('lang', lang)
+  return lang
+}
+
+export function loadLanguageAsync(lang) {
+  // 如果语言相同
+  if (i18n.locale === lang) {
+    return Promise.resolve(setI18nLanguage(lang))
+  }
+
+  // 如果语言已经加载
+  if (loadedLanguages.includes(lang)) {
+    return Promise.resolve(setI18nLanguage(lang))
+  }
+
+  // 如果尚未加载语言
+  return import(/* webpackChunkName: "lang-[request]" */ `@/i18n/messages/${lang}.js`).then(
+    messages => {
+      i18n.setLocaleMessage(lang, messages.default)
+      loadedLanguages.push(lang)
+      return setI18nLanguage(lang)
+    }
+  )
+}
+

简而言之,我们正在创建一个新的 VueI18n 实例。然后我们创建一个 loadedLanguages 数组,它将跟踪我们加载的语言。接下来是 setI18nLanguage 函数,它将实际更改 vueI18n 实例、axios 以及其它需要本地化的地方。

loadLanguageAsync 是实际用于更改语言的函数。加载新文件是通过import功能完成的,import 功能由 Webpack 慷慨提供,它允许我们动态加载文件,并且因为它使用 promise,我们可以轻松地等待加载完成。

你可以在 Webpack 文档 (opens new window) 中了解有关导入功能的更多信息。

使用 loadLanguageAsync 函数很简单。一个常见的用例是在 vue-router beforeEach 钩子里面。

router.beforeEach((to, from, next) => {
+  const lang = to.params.lang
+  loadLanguageAsync(lang).then(() => next())
+})
+

我们可以通过检查 lang 实际上是否支持来改进这一点,调用 reject 这样我们就可以在 beforeEach 捕获路由转换。

+ + + diff --git a/zh/guide/locale.html b/zh/guide/locale.html new file mode 100644 index 000000000..8f90b95df --- /dev/null +++ b/zh/guide/locale.html @@ -0,0 +1,127 @@ + + + + + + 语言环境变更 | Vue I18n + + + + + + + + + +

# 语言环境变更

通常,使用 Vue 根实例作为起点,使用 VueI18n 类的 locale 属性作为参考来本地化所有子组件。

有时你可能希望动态更改语言环境。在这种情况下,你可以更改 VueI18n 实例的 locale 属性的值。

const i18n = new VueI18n({
+  locale: 'ja', // 设置语言环境
+  ...
+})
+
+// 创建 Vue 根实例
+new Vue({
+  i18n,
+  ...
+}).$mount('#app')
+
+// 更改为其它的 locale
+i18n.locale = 'en'
+

每个组件都包含一个引用为 $i18n 属性的 VueI18n 实例,该实例也可用于更改语言环境。

示例:

<template>
+  <div class="locale-changer">
+    <select v-model="$i18n.locale">
+      <option v-for="(lang, i) in langs" :key="`Lang${i}`" :value="lang">
+        {{ lang }}
+      </option>
+    </select>
+  </div>
+</template>
+
+<script>
+export default {
+  name: 'locale-changer',
+  data () {
+    return { langs: ['ja', 'en'] }
+  }
+}
+</script>
+

警告

⚠️ 对于使用了 sync: false 的组件,语言环境的更改将被忽略。

组件与根范围

⚠️ 在组件内更改 $i18n.locale 不会更新根语言环境。 +如果您依靠根语言环境,例如在使用 root fallbacks 时,请使用 $root.$i18n.locale 而不是$ i18n.locale

+ + + diff --git a/zh/guide/messages.html b/zh/guide/messages.html new file mode 100644 index 000000000..ad40737cb --- /dev/null +++ b/zh/guide/messages.html @@ -0,0 +1,223 @@ + + + + + + 语言环境信息的语法 | Vue I18n + + + + + + + + + +

# 语言环境信息的语法

# 结构

语言环境信息的语法如下:

// 作为 Flowtype 定义,语言环境信息的语法类似于 BNF 注释
+type LocaleMessages = { [key: Locale]: LocaleMessageObject };
+type LocaleMessageObject = { [key: Path]: LocaleMessage };
+type LocaleMessageArray = LocaleMessage[];
+type MessageContext = {
+  list: (index: number) => mixed,
+  named: (key: string) => mixed,
+  linked: (key: string) => TranslateResult,
+  values: any,
+  path: string,
+  formatter: Formatter,
+  messages: LocaleMessages,
+  locale: Locale
+};
+type MessageFunction = (ctx: MessageContext) => string;
+type LocaleMessage = string | MessageFunction | LocaleMessageObject | LocaleMessageArray;
+type Locale = string;
+type Path = string;
+

基于以上语法,你可以配置以下结构的 Locale 信息:

{
+  "en": {  // 'en' Locale
+    "key1": "this is message1", // 基本的
+    "nested": { // 嵌套
+      "message1": "this is nested message1"
+    },
+    "errors": [ // 数组
+      "this is 0 error code message",
+      {  // 数组嵌套对象
+        "internal1": "this is internal 1 error message"
+      },
+      [  // 数组嵌套数组
+        "this is nested array error 1"
+      ]
+    ]
+  },
+  "ja": { // 'ja' Locale
+    // ...
+  }
+}
+

在上面的语言环境信息的结构中,你可以使用以下键名路径进行翻译。

<div id="app">
+  <!-- 基本的 -->
+  <p>{{ $t('key1') }}</p>
+  <!-- 嵌套 -->
+  <p>{{ $t('nested.message1') }}</p>
+  <!-- 数组 -->
+  <p>{{ $t('errors[0]') }}</p>
+  <!-- 数组嵌套对象 -->
+  <p>{{ $t('errors[1].internal1') }}</p>
+  <!-- 数组嵌套数组 -->
+  <p>{{ $t('errors[2][0]') }}</p>
+</div>
+

输出以下内容:

<div id="app">
+  <!-- 基本的 -->
+  <p>this is message1</p>
+  <!-- 嵌套 -->
+  <p>this is nested message1</p>
+  <!-- 数组 -->
+  <p>this is 0 error code message</p>
+  <!-- 数组嵌套对象 -->
+  <p>this is internal 1 error message</p>
+  <!-- 数组嵌套数组 -->
+  <p>this is nested array error 1</p>
+</div>
+

# Linked locale messages

如果有一个翻译关键字总是与另一个具有相同的具体文本,你可以链接到它。要链接到另一个翻译关键字,你所要做的就是在其内容前加上一个 @: 符号后跟完整的翻译键名,包括你要链接到的命名空间。

语言环境信息如下:

const messages = {
+  en: {
+    message: {
+      the_world: 'the world',
+      dio: 'DIO:',
+      linked: '@:message.dio @:message.the_world !!!!'
+    }
+  }
+}
+

模板如下:

<p>{{ $t('message.linked') }}</p>
+

输出如下:

<p>DIO: the world !!!!</p>
+

# 格式化链接的语言环境消息

如果语言区分字符大小写,则可能需要控制链接的语言环境消息的大小写。 +链接的消息可以用修饰符 @.modifier:key 格式化。

以下修饰符当前可用。

  • upper: 链接消息中的所有字符均大写
  • lower: 小写链接消息中的所有字符
  • capitalize: 大写链接消息中的第一个字符

语言环境消息如下:

const messages = {
+  en: {
+    message: {
+      homeAddress: 'Home address',
+      missingHomeAddress: 'Please provide @.lower:message.homeAddress'
+    }
+  }
+}
+
<label>{{ $t('message.homeAddress') }}</label>
+
+<p class="error">{{ $t('message.missingHomeAddress') }}</p>
+

输出以下内容:

<label>Home address</label>
+
+<p class="error">Please provide home address</p>
+

您可以添加修饰符或覆盖将 modifiers 选项传递给 VueI18n 构造函数的现有修饰符。

const i18n = new VueI18n({
+  locale: 'en',
+  modifiers: {
+    snakeCase: (str) => str.split(' ').join('-')
+  },
+  messages: {
+    // ...
+  },
+})
+

# 按括号分组

链接到的语言环境信息的键名也可以形如 @:(message.foo.bar.baz),其中链接到另一段翻译的键名在括号 () 里。

如果链接 @:message.something 后紧跟着一个点 .,则此选项非常有用,因为它本不该成为但却成为了链接的一部分。

语言环境信息如下:

const messages = {
+  en: {
+    message: {
+      dio: 'DIO',
+      linked: 'There\'s a reason, you lost, @:(message.dio).'
+    }
+  }
+}
+

模板如下:

<p>{{ $t('message.linked') }}</p>
+

输出如下:

<p>There's a reason, you lost, DIO.</p>
+

# 留言功能

vue-i18n 建议在翻译消息时使用基于列表的字符串或命名格式作为语言环境消息。

但是,在某些情况下,由于复杂的语言语法,您确实需要JavaScript的全部编程功能。 因此,您可以使用 message function 来代替基于字符串的消息。

以下是一个返回简单问候语的消息函数:

const messages = {
+  en: {
+    greeting: (ctx) => 'hello!'
+  }
+}
+

使用消息功能非常容易! 您只需使用 $tt 指定消息功能的键:

<p>{{ $t('greeting') }}</p>
+

输出如下:

<p>hello!</p>
+

消息功能输出消息,该消息具有消息功能的返回值。

# 命名格式

vue-i18n 支持命名格式 作为基于字符串的消息格式。 vue-i18n用$ t或t插值参数值,并可以将其输出。

使用 消息上下文 的消息功能可以完成以下操作:

这是问候的示例:

const messages = {
+  en: {
+    greeting: (ctx) => `hello, ${ctx.named('name')}!`
+  }
+}
+

模板:

<p>{{ $t('greeting', { name: 'DIO' }) }}</p>
+

输出如下:

<p>hello, DIO!</p>
+

消息上下文具有命名函数。 您需要指定键来解析以 $tt 命名的值。

# 清单格式

列表格式的使用类似于上述命名格式。

vue-i18n 支持 列表格式 作为基于字符串的消息格式。 vue-i18n用$ t或t插值参数值,并可以将其输出。

您可以通过使用消息上下文对消息函数执行相同的操作:

这是问候的示例:

const messages = {
+  en: {
+    greeting: (ctx) => `hello, ${ctx.list(0)}!`
+  }
+}
+

模板:

<p>{{ $t('greeting', ['DIO']) }}</p>
+

输出如下:

<p>hello, DIO!</p>
+

消息上下文具有列表功能。 您需要指定索引来解析由 $tt 列表指定的值。

# 局限性

在消息功能中,以下基于字符串提供的功能无法通过消息上下文使用:

  • 链接的区域设置消息
  • 复数
+ + + diff --git a/zh/guide/number.html b/zh/guide/number.html new file mode 100644 index 000000000..9e69e626e --- /dev/null +++ b/zh/guide/number.html @@ -0,0 +1,152 @@ + + + + + + 数字本地化 | Vue I18n + + + + + + + + + +

# 数字本地化

支持版本

🆕 7.0+ 新增

你可以使用你定义的格式来本地化数字。

数字格式如下:

const numberFormats = {
+  'en-US': {
+    currency: {
+      style: 'currency',
+      currency: 'USD'
+    }
+  },
+  'ja-JP': {
+    currency: {
+      style: 'currency',
+      currency: 'JPY',
+      currencyDisplay: 'symbol'
+    }
+  }
+}
+

如上,你可以指定具名的 (例如:currency 等) 的数字格式,并且需要使用 ECMA-402 Intl.NumberFormat 的选项 (opens new window)

之后就像语言环境信息一样,你需要指定 VueI18n 构造函数的 numberFormats 选项:

const i18n = new VueI18n({
+  numberFormats
+})
+
+new Vue({
+  i18n
+}).$mount('#app')
+

模板如下:

<div id="app">
+  <p>{{ $n(100, 'currency') }}</p>
+  <p>{{ $n(100, 'currency', 'ja-JP') }}</p>
+</div>
+

输出如下:

<div id="app">
+  <p>$100.00</p>
+  <p>¥100</p>
+</div>
+

# 自定义格式

支持版本

🆕 8.10+ 新增

$n 方法返回的结果字符串带有完全格式化的数字,该数字只能作为整体使用。 在需要格式化格式化数字的某些部分(例如小数位)的情况下,$n 是不够的。 在这种情况下,<i18n-n> 功能组件将有所帮助。

有了最少的一组属性,<i18n-n> 产生的输出与 $n 相同,并包装到已配置的DOM元素中。

以下模板:

<div id="app">
+  <i18n-n :value="100"></i18n-n>
+  <i18n-n :value="100" format="currency"></i18n-n>
+  <i18n-n :value="100" format="currency" locale="ja-JP"></i18n-n>
+</div>
+

将产生以下输出:

<div id="app">
+  <span>100</span>
+  <span>$100.00</span>
+  <span>¥100</span>
+</div>
+

但是,当与范围内的插槽 (opens new window) 一起使用时,该组件的真正功能就会发挥作用。

假设需要用较粗的字体呈现数字的整数部分。 这可以通过指定 integer 作用域的插槽元素来实现:

<i18n-n :value="100" format="currency">
+  <span v-slot:integer="slotProps" styles="font-weight: bold">{{ slotProps.integer }}</span>
+</i18n-n>
+

上面的模板将产生以下 HTML:

<span>$<span styles="font-weight: bold">100</span>.00</span>
+

可以同时指定多个作用域插槽:

<i18n-n :value="1234" :format="{ key: 'currency', currency: 'EUR' }">
+  <span v-slot:currency="slotProps" styles="color: green">{{ slotProps.currency }}</span>
+  <span v-slot:integer="slotProps" styles="font-weight: bold">{{ slotProps.integer }}</span>
+  <span v-slot:group="slotProps" styles="font-weight: bold">{{ slotProps.group }}</span>
+  <span v-slot:fraction="slotProps" styles="font-size: small">{{ slotProps.fraction }}</span>
+</i18n-n>
+

(此结果 HTML 进行了格式化,以提高可读性)

<span>
+  <span styles="color: green"></span>
+  <span styles="font-weight: bold">1</span>
+  <span styles="font-weight: bold">,</span>
+  <span styles="font-weight: bold">234</span>
+  <span styles="font-size: small">00</span>
+</span>
+

您可以通过指定 tag 属性来选择根容器的节点类型。 如果省略,则默认为 'span'。 您也可以将其设置为布尔值 false 以直接插入子节点,而无需创建根元素。

可以在 API 页面 中找到受支持的作用域插槽以及其他 <i18n-n> 属性的完整列表。

+ + + diff --git a/zh/guide/pluralization.html b/zh/guide/pluralization.html new file mode 100644 index 000000000..1e02f0ddc --- /dev/null +++ b/zh/guide/pluralization.html @@ -0,0 +1,191 @@ + + + + + + 复数 | Vue I18n + + + + + + + + + +

# 复数

你可以使用复数进行翻译。你必须定义具有管道 | 分隔符的语言环境,并在管道分隔符中定义复数。

*您的模板将需要使用 $tc() 而不是 $t()

语言环境信息如下:

const messages = {
+  en: {
+    car: 'car | cars',
+    apple: 'no apples | one apple | {count} apples'
+  }
+}
+

模板如下:

<p>{{ $tc('car', 1) }}</p>
+<p>{{ $tc('car', 2) }}</p>
+
+<p>{{ $tc('apple', 0) }}</p>
+<p>{{ $tc('apple', 1) }}</p>
+<p>{{ $tc('apple', 10, { count: 10 }) }}</p>
+

输出如下:

<p>car</p>
+<p>cars</p>
+
+<p>no apples</p>
+<p>one apple</p>
+<p>10 apples</p>
+

# 通过预定义的参数访问该数字

你无需明确指定复数的数字。可以通过预定义的命名参数 {count} 和/或 {n} 在语言环境信息中访问该数字。如有必要,你可以覆盖这些预定义的命名参数。

语言环境信息如下:

const messages = {
+  en: {
+    apple: 'no apples | one apple | {count} apples',
+    banana: 'no bananas | {n} banana | {n} bananas'
+  }
+}
+

模板如下:

<p>{{ $tc('apple', 10, { count: 10 }) }}</p>
+<p>{{ $tc('apple', 10) }}</p>
+
+<p>{{ $tc('banana', 1, { n: 1 }) }}</p>
+<p>{{ $tc('banana', 1) }}</p>
+<p>{{ $tc('banana', 100, { n: 'too many' }) }}</p>
+

输出如下:

<p>10 apples</p>
+<p>10 apples</p>
+
+<p>1 banana</p>
+<p>1 banana</p>
+<p>too many bananas</p>
+

# 自定义复数

但是,这种多元化并不适用于所有语言(例如,斯拉夫语言具有不同的多元化规则)。

为了实现这些规则,您可以将可选的 pluralizationRules 对象传递给VueI18n 构造函数选项。

使用针对斯拉夫语言(俄语,乌克兰语等)的规则的非常简化的示例:

new VueI18n({
+  // Key - 在这种情况下,用于规则 `'ru'` 的语言
+  // Value - 选择正确的复数形式的功能
+  pluralizationRules: {
+    /**
+     * @param choice {number} 输入给$的选择索引 $tc:`$tc('path.to.rule', choiceIndex)`
+     * @param choicesLength {number} 可用选择总数
+     * @returns 最终选择索引以选择复数单词
+     */
+    'ru': function(choice, choicesLength) {
+      // this === VueI18n 实例,因此本地属性也存在于此
+
+      if (choice === 0) {
+        return 0;
+      }
+
+      const teen = choice > 10 && choice < 20;
+      const endsWithOne = choice % 10 === 1;
+
+      if (choicesLength < 4) {
+        return (!teen && endsWithOne) ? 1 : 2;
+      }
+      if (!teen && endsWithOne) {
+        return 1;
+      }
+      if (!teen && choice % 10 >= 2 && choice % 10 <= 4) {
+        return 2;
+      }
+
+      return (choicesLength < 4) ? 2 : 3;
+    }
+  }
+})
+

这将有效地实现以下目的:

const messages = {
+  ru: {
+    car: '0 машин | {n} машина | {n} машины | {n} машин',
+    banana: 'нет бананов | {n} банан | {n} банана | {n} бананов'
+  }
+}
+

格式在哪里 0 东西 | 事情以结尾结束 1 | 事情以结尾结束 2-4 | 事情以结尾结束 5-9, 0 和青少年 (10-19). +附言 斯拉夫多元化是困难的,您可以阅读有关它的更多信息 这里 (opens new window).

你的模板仍然需要使用 $tc(),而不是 $t()

<p>{{ $tc('car', 1) }}</p>
+<p>{{ $tc('car', 2) }}</p>
+<p>{{ $tc('car', 4) }}</p>
+<p>{{ $tc('car', 12) }}</p>
+<p>{{ $tc('car', 21) }}</p>
+
+<p>{{ $tc('banana', 0) }}</p>
+<p>{{ $tc('banana', 4) }}</p>
+<p>{{ $tc('banana', 11) }}</p>
+<p>{{ $tc('banana', 31) }}</p>
+

结果如下:

<p>1 машина</p>
+<p>2 машины</p>
+<p>4 машины</p>
+<p>12 машин</p>
+<p>21 машина</p>
+
+<p>нет бананов</p>
+<p>4 банана</p>
+<p>11 бананов</p>
+<p>31 банан</p>
+

# 默认多元

如果在多元化地图中找不到您当前的语言环境,则将使用英语的 默认 规则。

+ + + diff --git a/zh/guide/sfc.html b/zh/guide/sfc.html new file mode 100644 index 000000000..bb3226052 --- /dev/null +++ b/zh/guide/sfc.html @@ -0,0 +1,379 @@ + + + + + + 单文件组件 | Vue I18n + + + + + + + + + +

# 单文件组件

# 基本用法

如果使用单文件组件构建 Vue 组件或 Vue 应用程序,则可以管理 i18n 自定义块的语言环境信息。

以下是单文件组件示例 (opens new window):

<i18n>
+{
+  "en": {
+    "hello": "hello world!"
+  },
+  "ja": {
+    "hello": "こんにちは、世界!"
+  }
+}
+</i18n>
+
+<template>
+  <div id="app">
+    <label for="locale">locale</label>
+    <select v-model="locale">
+      <option>en</option>
+      <option>ja</option>
+    </select>
+    <p>message: {{ $t('hello') }}</p>
+  </div>
+</template>
+
+<script>
+export default {
+  name: 'app',
+  data () { return { locale: 'en' } },
+  watch: {
+    locale (val) {
+      this.$i18n.locale = val
+    }
+  }
+}
+</script>
+

# 安装 vue-i18n-loader

为了使用 <i18n> 自定义块,你需要安装 vue-loadervue-i18n-loader。如果你使用了单文件组件,vue-loader (opens new window) 很可能已在项目中使用了,那么 vue-i18n-loader (opens new window) 必须另外安装:

npm i --save-dev @kazupon/vue-i18n-loader
+

# Webpack

需要对 Webpack 进行以下配置:

对于 vue-loader v15 或更高版本:

module.exports = {
+  // ...
+  module: {
+    rules: [
+      {
+        test: /\.vue$/,
+        loader: 'vue-loader',
+      },
+      {
+        resourceQuery: /blockType=i18n/,
+        type: 'javascript/auto',
+        loader: '@kazupon/vue-i18n-loader'
+      }
+      // ...
+    ]
+  },
+  // ...
+}
+

对于 vue-loader v14:

module.exports = {
+  // ...
+  module: {
+    rules: [
+      {
+        test: /\.vue$/,
+        loader: 'vue-loader',
+        options: {
+          loaders: {
+            // 你需要指定 `i18n` 的值为 `vue-i18n-loader`
+            i18n: '@kazupon/vue-i18n-loader'
+          }
+        }
+      },
+      // ...
+    ]
+  },
+  // ...
+}
+

# Vue CLI 3.0

Vue CLI 3.0 (opens new window) 隐藏了 webpack 配置,因此,如果我们想在单文件组件中添加对 <i18n> 标记的支持,我们需要修改现有配置。

为此,我们必须在项目的根目录下创建一个 vue.config.js。完成后,我们必须包括以下内容:

对于 vue-loader v15 或更高版本:

module.exports = {
+  chainWebpack: config => {
+    config.module
+      .rule("i18n")
+      .resourceQuery(/blockType=i18n/)
+      .type('javascript/auto')
+      .use("i18n")
+        .loader("@kazupon/vue-i18n-loader")
+        .end();
+  }
+}
+

对于 vue-loader v14:

const merge = require('deepmerge')
+
+module.exports = {
+  chainWebpack: config => {
+    config.module
+      .rule('vue')
+      .use('vue-loader')
+      .tap(options =>
+        merge(options, {
+          loaders: {
+            i18n: '@kazupon/vue-i18n-loader'
+          }
+        })
+      )
+  }
+}
+

别忘了安装deepmerge (opens new window)! (npm i deepmerge -Dyarn add deepmerge -D)

如果你想了解有关修改现有配置的更多信息点击这里 (opens new window)

# Laravel-Mix

对于带有 vue-loader v15 或更高版本的 Laravel-mix 4:

// 使用 “i18n” 方法扩展 Mix ,加载 vue-i18n-loader
+mix.extend( 'i18n', new class {
+        webpackRules() {
+            return [
+                {
+                    resourceQuery: /blockType=i18n/,
+                    type:          'javascript/auto',
+                    loader:        '@kazupon/vue-i18n-loader',
+                },
+            ];
+        }
+    }(),
+);
+
+// 确保在 `.js(..., ...)` 之前调用 `.i18n()` (来加载加载器)
+mix.i18n()
+   .js( 'resources/js/App.js', 'public/js/app.js' )
+   ...
+

对于带有 vue-loader v14 的 Laravel-mix 2:

从 Laravel-mix 的 V2.1 (opens new window) 开始,你可以通过 mix.extend() 添加自定义规则。Laravel mix 已经有了处理 .vue 文件的规则。要添加 vue-i18n-loader,请将以下内容添加到 webpack.mix.js

// 下面的代码将注入 i18n Kazupon/vue-18-loader 作为 .vue 文件的加载器。
+mix.extend( 'i18n', function( webpackConfig, ...args ) {
+    webpackConfig.module.rules.forEach( ( module ) => {
+        // 搜索处理 .vue 文件的 “vue-loader” 组件。
+        if( module.loader !== 'vue-loader' ) {
+            return;
+        }
+
+        // 在此模块中,为 i18n 标记添加 vue-i18n-loader。
+        module.options.loaders.i18n = '@kazupon/vue-i18n-loader';
+    } );
+} );
+
+// 确保在 `.js(...,...)` 之前调用 `.i18n()`
+mix.i18n()
+   .js( 'resources/assets/js/App.js', 'public/js/app.js' )
+   ...
+

# 加载 YAML

i18n 自定义块需要指定为 JSON 格式,你也可以通过使用 vue-loader 预加载器功能来使用 YAML 格式。

以下是 YAML 格式的 i18n 自定义块:

<i18n>
+en:
+  hello: "hello world!"
+ja:
+  hello: "こんにちは、世界!"
+</i18n>
+

Webpack 配置如下:

对于 vue-loader v15 或更高版本:

// Vue CLI 3.0
+module.exports = {
+  chainWebpack: config => {
+    config.module
+      .rule("i18n")
+      .resourceQuery(/blockType=i18n/)
+      .type('javascript/auto')
+      .use("i18n")
+        .loader("@kazupon/vue-i18n-loader")
+        .end()
+      .use('yaml')
+        .loader('yaml-loader')
+        .end()
+  }
+}
+

对于 vue-loader v14:

module.exports = {
+  // ...
+  module: {
+    rules: [
+      {
+        test: /\.vue$/,
+        loader: 'vue-loader',
+        options: {
+          preLoaders: {
+            i18n: 'yaml-loader'
+          },
+          loaders: {
+            i18n: '@kazupon/vue-i18n-loader'
+          }
+        }
+      },
+      // ...
+    ]
+  },
+  // ...
+}
+

# 多个自定义块

你可以使用具有多个 i18n 自定义块的语言环境信息。

<i18n src="./common/locales.json"></i18n>
+<i18n>
+  {
+    "en": {
+      "hello": "hello world!"
+    },
+    "ja": {
+      "hello": "こんにちは、世界!"
+    }
+  }
+</i18n>
+

如上所见,第一个自定义块使用 src 特性加载常用的语言环境信息,第二个自定义块加载仅在该单文件组件中定义的语言环境信息。这些语言环境信息将合并为组件的语言环境信息。

这样,多个自定义块在想要用作模块时非常有用。

# Scoped 风格

当使用带有 scoped style vue-i18n 时,重要的是要记住使用深度选择器 (opens new window) 来设置嵌套转换的样式。例如:

翻译仅包含文本(不使用深层选择器)

<i18n>
+{
+  "en": {
+    "hello": "hello world!"
+  },
+  "ja": {
+    "hello": "こんにちは、世界"
+  }
+}
+</i18n>
+
+<template>
+  <div class="parent">
+    <p>message: {{ $t('hello') }}</p>
+  </div>
+</template>
+
+<!-- 可行 -->
+<style scoped>
+  .parent p {
+    color: #42b883;
+  }
+</style>
+

使用 HTML 元素翻译(必须使用深度选择器)

<i18n>
+{
+  "en": {
+    "hello": "hello<span>world!</span>"
+  },
+  "ja": {
+    "hello": "こんにちは、<span>世界!</span>"
+  }
+}
+</i18n>
+
+<template>
+  <div class="parent">
+    <p v-html="$t('hello')"></p>
+  </div>
+</template>
+
+<!-- 不可行-->
+<style scoped>
+  .parent p {
+    color: #42b883;
+  }
+
+  .parent p span {
+    color: red;
+  }
+</style>
+
+<!-- 可行 >>> -->
+<style scoped>
+  .parent p {
+    color: #42b883;
+  }
+
+  .parent p >>> span {
+    color: red;
+  }
+</style>
+
+<!-- 可行 /deep/ -->
+<style scoped>
+  .parent p {
+    color: #42b883;
+  }
+
+  .parent p /deep/ span {
+    color: red;
+  }
+</style>
+
+<!-- 可行 ::v-deep -->
+<style scoped>
+  .parent p {
+    color: #42b883;
+  }
+
+  ::v-deep .parent p span {
+    color: red;
+  }
+</style>
+

# 函数式组件中的自定义块

如果单个文件组件具有使用函数式组件的模板,并且你已经定义了 i18n 自定义块,请注意你无法使用语言环境信息进行本地化。

例如,以下代码无法使用 i18n 自定义块的语言环境信息进行本地化。

<i18n>
+{
+  "en": {
+    "hello": "hello world"
+  },
+  "ja": {
+    "hello": "こんにちは、世界"
+  }
+}
+</i18n>
+
+<template functional>
+  <!-- 'hello' 的父实例的语言环境信息 -->
+  <p>{{ parent.$t('hello') }}</p>
+</template>
+
+ + + diff --git a/zh/guide/tooling.html b/zh/guide/tooling.html new file mode 100644 index 000000000..e7c82d607 --- /dev/null +++ b/zh/guide/tooling.html @@ -0,0 +1,92 @@ + + + + + + 工具 | Vue I18n + + + + + + + + + +

# 工具

为了支持开发,我们官方提供了一些工具。

此外,还有第三方供应商提供的集成了 Vue I18n 的工具。

# 官方工具

# Vue Cli 插件

vue-cli-plugin-i18n (opens new window) 是官方提供的 Vue Cli 插件。

使用此插件,您可以为Vue应用程序设置 i18n 环境,并支持 i18n 开发环境。

# Webpack Loader

vue-i18n-loader (opens new window) 是官方提供的 Webpack Loader。 +使用此加载程序,您可以在单个文件组件中使用 i18n 自定义块。

关于 i18n 自定义块,请参见 单文件组件

# ESLint 插件

eslint-plugin-vue-i18n (opens new window) 是为 Vue I18n 编写的 ESLint 插件。

它可以轻松地将一些本地化 lint 功能集成到 Vue.js 应用程序中。

# Extensions

vue-i18n-extensions (opens new window) 你可以找到为 Vue I18n 编写的插件。

您可以使用此扩展来启用 SSR 并提高 Vue I18n 的性能。

# 第三方工具

# BabelEdit

BabelEdit (opens new window) 是 Web 应用程序的翻译编辑器。

BabelEdit可以翻译 json 文件,也可以翻译单文件组件的 i18n 自定义块。

欲了解更多,请看教程 (opens new window)

# i18n Ally

i18n Ally (opens new window) 是 VSCode 的 i18n 扩展。

i18n Ally 为您的 i18n 开发提供了出色的 DX。

自述文件 (opens new window)中了解有关 i18n Ally 的更多信息。

# i18nPlugin (intellij 平台)

i18nPlugin (opens new window) Intellij idea i18next 支持插件(Jetbrains 插件页面 (opens new window))。

适用于 i18n typescript/javascript/PHP 的插件。 支持 vue-i18n。 要启用 vue-i18n 支持,请转到 设置- > 工具 -> i18n 插件配置,然后选中 "Vue-i18n"。 您需要设置您的语言环境目录(默认为语言环境)。

# vue-i18n-extract

vue-i18n-extract (opens new window) 对基于 vue-i18n 的 Vue.js 项目执行静态分析,并报告以下信息:

  • 所有 未使用的 vue-i18n 键的列表(在语言文件中找到但在项目中未使用的条目)
  • 所有 缺失键 的列表(在项目中使用但在语言文件中不存在的条目)

可以在控制台中显示输出或将其写入json文件

丢失的键也可以自动添加到给定的语言文件中

+ + + diff --git a/zh/index.html b/zh/index.html new file mode 100644 index 000000000..fa34ce26b --- /dev/null +++ b/zh/index.html @@ -0,0 +1,97 @@ + + + + + + Vue I18n + + + + + + + + + +
hero

+ Vue I18n +

+ Vue I18n 是 Vue.js 的国际化插件 +

+ 快速上手 → +

🥇 金牌赞助商

Nuxt.js

🥈 白银赞助商

适用于应用程序(Web应用程序)的BabelEdit翻译编辑器

🥉 青铜赞助商

zenarchitects sendcloud

简单

通过简单的 API 将你的应用国际化

强大

除了简单的翻译外,还支持复数,数字,日期时间等本地化处理

面向组件

你可以在单文件组件上管理语言环境信息

+ + + diff --git a/zh/installation.html b/zh/installation.html new file mode 100644 index 000000000..2d71a44fd --- /dev/null +++ b/zh/installation.html @@ -0,0 +1,109 @@ + + + + + + 安装 | Vue I18n + + + + + + + + + +

# 安装

# 兼容性说明

  • Vue.js 2.0.0+

# 直接下载 / CDN

https://unpkg.com/vue-i18n/dist/vue-i18n (opens new window)

unpkg.com (opens new window) 提供了基于 NPM 的 CDN 链接。上面的链接会一直指向在 NPM 发布的最新版本。你也可以通过 https://unpkg.com/vue-i18n@8.9.0/dist/vue-i18n.js (opens new window) 这样的 URL 指定版本号或者 tag。

在 Vue 之后引入 vue-i18n,它会自动安装:

<script src="https://unpkg.com/vue/dist/vue.js"></script>
+<script src="https://unpkg.com/vue-i18n/dist/vue-i18n.js"></script>
+

# NPM

npm install vue-i18n
+

# Yarn

yarn add vue-i18n
+

如果在一个模块系统中使用它,你必须通过 Vue.use() 明确地安装 vue-i18n

import Vue from 'vue'
+import VueI18n from 'vue-i18n'
+
+Vue.use(VueI18n)
+

如果使用全局的 script 标签,则无须如此 (手动安装) <script>

# Vue Cli 3.x

vue add i18n
+

你需要 Vue cli 3.x 作为先决条件,你可以在命令行上使用下面的命令来安装:

npm install @vue/cli -g
+

# 开发版构建

如果你想使用最新的开发版构建,就得从 GitHub 上直接 clone,然后自己构建一个 vue-i18n

git clone https://github.com/kazupon/vue-i18n.git node_modules/vue-i18n
+cd node_modules/vue-i18n
+npm install # or `yarn`
+npm run build  # or `yarn run build`
+
+ + + diff --git a/zh/introduction.html b/zh/introduction.html new file mode 100644 index 000000000..7fd7ef175 --- /dev/null +++ b/zh/introduction.html @@ -0,0 +1,91 @@ + + + + + + 介绍 | Vue I18n + + + + + + + + + +

# 介绍

说明

⚠️ 本文档适用于 Vue I18n v6.0 或更高版本. 如果你使用 v5.x,请参阅旧版部分。

Vue I18n 是 Vue.js 的国际化插件。它可以轻松地将一些本地化功能集成到你的 Vue.js 应用程序中。

让我们开始吧

# 赞助商

# 🥇 金

Nuxt.js

# 🥈 白银赞助商

适用于应用程序(Web应用程序)的BabelEdit翻译编辑器

# 🥉 青铜

zenarchitects sendcloud

# 成为一名 Patreon 赞助商

贵公司是否使用 vue-i18n 或 vue-cli-plugin-i18n 来构建出色的应用程序? 加入其他会员并成为赞助商,在此文档中添加你的徽标!在 Patreon 上支持我使我能够更少地完成工作并在免费开源软件上工作,例如 vue-i18n! 谢谢!

+ + + diff --git a/zh/started.html b/zh/started.html new file mode 100644 index 000000000..7f74870bd --- /dev/null +++ b/zh/started.html @@ -0,0 +1,135 @@ + + + + + + 开始 | Vue I18n + + + + + + + + + +

# 开始

说明

我们将在指南中的代码示例中使用 ES2015 (opens new window) 语法。

# HTML

<script src="https://unpkg.com/vue/dist/vue.js"></script>
+<script src="https://unpkg.com/vue-i18n/dist/vue-i18n.js"></script>
+
+<div id="app">
+  <p>{{ $t("message.hello") }}</p>
+</div>
+

# JavaScript

// 如果使用模块系统 (例如通过 vue-cli),则需要导入 Vue 和 VueI18n ,然后调用 Vue.use(VueI18n)。
+// import Vue from 'vue'
+// import VueI18n from 'vue-i18n'
+//
+// Vue.use(VueI18n)
+
+// 准备翻译的语言环境信息
+const messages = {
+  en: {
+    message: {
+      hello: 'hello world'
+    }
+  },
+  ja: {
+    message: {
+      hello: 'こんにちは、世界'
+    }
+  }
+}
+
+// 通过选项创建 VueI18n 实例
+const i18n = new VueI18n({
+  locale: 'ja', // 设置地区
+  messages, // 设置地区信息
+})
+
+
+// 通过 `i18n` 选项创建 Vue 实例
+new Vue({ i18n }).$mount('#app')
+
+// 现在应用程序已经准备好了!
+

输出如下:

<div id="#app">
+  <p>こんにちは、世界</p>
+</div>
+
+ + +