Search code examples
vue.jsinternationalizationvuetify.jsvue-i18n

How to Translate Vue i18n of v-for data Array of String


I am new to vuejs and doing my project with multi language feature, German and English, but I have problem with data Array of String which is loops through of a lists, and I don't know how to translate it, here's what I meant

export default {
  name: "HelloWorld",

  data() {
    return {
      items: [
        {
          text: "Explore Components",
          name: "vuetifyjs vuetify-loader",
        },
        {
          text: "Select a layout",
          name: "vuetifyjs vuetify",
        },
        {
          text: "Frequently Asked Questions",
          name: "vuetifyjs awesome-vuetify",
        },
      ],
    };
  },
};

I want to translate the items.text in German and English, and here's my de.json and en.json

// de.json
{
  "whatsNext": {
    "components": "Komponenten erforschen",
    "selectLayout": "Layout wählen",
    "frequentQuestion": "Häufig gestellte Fragen"
  }
}

// en.json
{
"whatsNext": {
    "components": "Explore components",
    "selectLayout": "Select a layout",
    "frequentQuestion": "Frequently Asked Questions"
  }
}

normally you can just {{ $t('whatsNext.components') }} but since it loops in v-for I don't know how, can someone help?

I tried this but it doesn't work and only renders german, since the locale in German

data() {
    return {
      items: [
        {
          text: this.$root.$t("whatsNext.components"),
          name: "vuetifyjs vuetify-loader",
        },
        {
          text: this.$root.$t("whatsNext.selectLayout"),
          name: "vuetifyjs vuetify",
        },
        {
          text: this.$root.$t("whatsNext.frequentQuestion"),
          name: "vuetifyjs awesome-vuetify",
        },
      ],
    };
  },

Solution

  • I'd not translate the texts in data() but instead only include the static translation keys there:

    data() {
      return {
        items: [
          {
            text_key: "whatsNext.components",
            name: "vuetifyjs vuetify-loader",
          },
          {
            text_key: "whatsNext.selectLayout",
            name: "vuetifyjs vuetify",
          },
          {
            text_key: "whatsNext.frequentQuestion",
            name: "vuetifyjs awesome-vuetify",
          },
        ],
      };
    },
    

    And then, in your template:

    <ul>
      <li v-for="item in items" :key="item.text_key">
        {{ $t(item.text_key) }}
      </li>
    </ul>