useVIntl
useVIntl
is a composable that is automatically imported when using VIntl for Nuxt. When used, it injects the active VIntl instance, which can be used to provide internationalisation capabilities, such as formatMessage
function, or access to the current state of the controller (e.g. locale
).
Examples
Here are a few examples showcasing useVIntl
usage.
Basic usage
<script setup lang="ts">
const { formatMessage } = useVIntl()
const greeting = defineMessage({
id: 'greeting',
defaultMessage: 'Hello, {name}!',
})
</script>
<template>
<div>{{ formatMessage(greeting, { name: 'Alex' }) }}</div>
</template>
In the example above, we use formatMessage
to format a translated message with a variable. We define our message using the defineMessage
function.
Accessing the current locale
<script setup lang="ts">
const vintl = useVIntl()
const locale = computed(() => vintl.locale)
</script>
<template>
<div>{{ locale }}</div>
</template>
In this example, we use useVIntl
to access the current locale and display it in the component.
Writing a list component
<script setup lang="ts">
const { formats: fmt } = useVIntl()
const props = defineProps<{
items: string[]
type?: 'conjunction' | 'disjunction' | 'unit'
}>()
const list = computed(() =>
fmt.list(props.items, {
type: props.type,
}),
)
</script>
<template>{{ list }}</template>
Here we used destructuring to get the formats
property of the controller, which contains the aliases for formatters. We also define items
and type
props. items
will contain list items, and type
will declare how the list will be rendered. We then use computed
, where we format the list, this will help us avoid useless re-renders. In the end we get a <List>
component that we can use to render lists of various items.