I am starting to use the Vue i18n plugin and everything was going smoothly until I had to iterate over an array to render Vue components with a v-for directive.
The array with the objects (one per component) containing the strings to be passed as props to said components has this structure:
{
"abouts": [
{
"title": "Title1",
"description": "Description1"
},
{
"title": "Title2",
"description": "Description2"
},
...
],
}
So at the end, what I want to do is to have a component being rendered via a v-for directive as many times as there are objects within the array in ‘abouts’, passing the localized strings as props to the component. Something like this:
<AboutBox v-for="about in abouts" :title="about.title" :description="about.description" />
I was reading the documentation and so far I cannot make heads nor tails of it. I know I have to use tm
and rt
as documented here: https://vue-i18n.intlify.dev/api/composition.html#tm-key and in the migration guide fo v9 https://vue-i18n.intlify.dev/guide/migration/breaking#translation-api-return-value.
I tried using that for my template and I wrote this:
<AboutBox
v-for="(about, index) in abouts"
:key="index"
:title="$rt(about.title)"
:description="$rt(about.description)"
/>
While my script look like this:
import type { About } from '@/plugins/i18n'
import AboutBox from './AboutBox.vue'
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
// Accessing i18n
const { tm } = useI18n()
const abouts = computed(() => tm('abouts') as About[])
Where the About
type is:
interface About {
title: string
description: string
}
And I used a computed property because otherwise the data is not reactive.
With this code everything works as expected but I am not really sure that I am doing it the way it is supposed to be done (I don’t really understand that documentation fully). If someone with more experience, or another solution, can provide their insight, I thank you.