id | title |
---|---|
vue-intl |
Vue Plugin for formatjs |
This library contains our plugin for Vue.
import Tabs from '@theme/Tabs' import TabItem from '@theme/TabItem'
<Tabs groupId="npm" defaultValue="npm" values={[ {label: 'npm', value: 'npm'}, {label: 'yarn', value: 'yarn'}, ]}>
npm i -S @formatjs/vue-intl
yarn add -S @formatjs/vue-intl
Initialize VueIntl
plugin with the same IntlConfig
documented in @formatjs/intl.
import VueIntl from '@formatjs/vue-intl'
const app = createApp(App)
app.use(VueIntl, {
locale: 'en',
defaultLocale: 'en',
messages: {
foo: 'bar',
},
})
From there you can use our APIs in 2 ways:
By specifying inject: ['intl']
, you can use the full IntlFormatters
API documented in @formatjs/intl.
We also support Vue's Composition API with provideIntl
& useIntl
.
import {createIntl} from '@formatjs/intl'
import {provideIntl, useIntl} from '@formatjs/vue-intl'
const Ancestor = {
setup() {
provideIntl(
createIntl({
locale: 'en',
defaultLocale: 'en',
messages: {
foo: 'Composed',
},
})
)
},
render() {
return h(Descendant)
},
}
const Descendant = {
setup() {
const intl = useIntl()
return () =>
h(
'p',
{},
intl.formatMessage({
id: 'foo',
defaultMessage: 'Hello',
})
)
},
}
You can also use our formatters in Vue template by prepending $
like below:
<template>
<p>{{ $formatNumber(3, {style: 'currency', currency: 'USD'}) }}</p>
</template>
We currently support:
$formatMessage
$formatDate
$formatTime
$formatRelativeTime
$formatTimeRange
$formatDisplayName
$formatList
We're actively working on adding vue
support for formatjs toolchain. Currently the following tools are supported:
- eslint-plugin-formatjs: This fully supports
.vue
and JS/TS.
Since }}
& {{
are special tokens in .vue
<template>
, this can cause potential conflict with ICU MessageFormat syntax, e.g:
<template>
<p>
{{ $formatMessage({ defaultMessage: '{count, selectordinal, offset:1 one {#}
other {# more}}', }) }}
</p>
</template>
Notice the {# more}}
where it ends with }}
. This will cause parsing issue in your vue
template. In order to work around this issue, we recommend using space to turn }}
into } }
.
<template>
<p>
{{
$formatMessage({
defaultMessage:
'{count, selectordinal, offset:1 one {#} other {# more} }',
})
}}
</p>
</template>