Search code examples
vue.jsvue-i18n

Vue I18n multi language


I'm doing multi-language support with vue js, everything works fine, but when I change the language, the data in the data menuItem name does not change.

Vuei18n

<template v-slot:MenuItem>
    <MenuItems v-for="(Item,Index) in menuItem"
               :key="Index"
               :items="Item"
               :depth="Index"
    >
        <router-link :to="Item.path">{{Item.name}}</router-link>
    </MenuItems>
</template>

export default {
    name: "Nav",
    data() {
        return {
            menuItem: [
                {
                    name: this.$t('navbar.home'),
                    path: '',
                },
                {
                    name: this.$t('navbar.gallery'),
                    path: 'gallery',
                },
                {
                    name: this.$t('navbar.contact'),
                    path: 'contact',
                },
            ],
        }
    }
}

Solution

  • data() is only called once when creating the component, and it's not intended to be reactive. (So basically when your component is being created, it gets the your current translation as initial values)

    To make a property reactive on $t(), you should use computed var instead:

      export default {
        name: "Nav",
        data() {
          // exclude from here
          return {};
        },
        computed: {
          menuItem() {
            return [
              {
                name: this.$t("navbar.home"),
                path: "",
              },
              {
                name: this.$t("navbar.gallery"),
                path: "gallery",
              },
              {
                name: this.$t("navbar.contact"),
                path: "contact",
              },
            ];
          },
        },
      };