Dav Corre
Dav Corre

Reputation: 31

vue v-for: translate with switch in vue i18n

I have a problem to translate the information with vue i18n that is called through "v-for", all the data from the template is translated without problem, but those that I export through arrays and scripts do not render

i am using vue-i18n: version 7.8.1

Upvotes: 2

Views: 3429

Answers (1)

Phil
Phil

Reputation: 164897

You're only ever setting the helpTitles property when your component is created.

I would suggest using $t() in your templates instead of within data(). Then it will automatically react to changes.

I honestly don't think using an array from the translation file is a great idea. I'd be more inclined to add them with their own keys, just like your question and info translation keys, eg

helpStartedTitle: "GETTING STARTED - MODEL",
helpMembersTitle: "MEMBERS",
helpAccountTitle: "ACCOUNT",
//etc

You could then set up the keys in your data like this

data: () => {
  const keys = [
    "helpStarted",
    "helpMembers",
    "helpAccount", 
    "helpPayment", 
    "helpSocial", 
    "helpFraud", 
    "helpSupport",
    "helpStudio"
  ]

  return {
    helpInfo: keys.map((key, id) => ({
      id,
      title: `general.help.${key}Title`,
      question: `general.help.${key}`,
      answer: `general.help.${key}Info`
    }))
  }
}

then in your template

<div v-for="help in helpInfo" :key="help.id">
  <div :id="help.id" class="help-subtitle">{{ $t(help.title) }}:</div>
  <HelpItem
    :question="$t(help.question)"
    :answer="$t(help.answer)"
    :num="help.id"
  />
</div>

Even better would be to just pass the translation keys through to your HelpItem component and use $t() with it.

<HelpItem
  :question="help.question"
  :answer="help.answer"
  :num="help.id"
/>

and in the HelpItem component

export default {
  name: "HelpItem",
  props: {
    question: String,
    answer: String,
    num: Number
  },
  // etc
}
<!-- just guessing here -->
<h1>{{ $t(question) }}</h1>
<p>{{ $t(answer) }}</p>

FYI, I've corrected answear to answer throughout.

Upvotes: 2

Related Questions