mateuscad
mateuscad

Reputation: 11

Vue i18n - object with translation variables in js file

i'm working with Vue, Vue i18n and Quasar.

So, i have an js file that contains an object with id and name, which i use on q-select options. I want that when i change the language (on language drop-down), the label name from months changes too. But this happens only if i refresh the page. I use the same js file in other components

Vue component:

<q-select
  v-model="monthValue"
  :options="monthOptions()"
  map-options
  emit-value
  option-value="id"
  option-label="name"
  outlined
  dense
/>
import {getMonths} from "../../components/basic/Months.js";
computed: {
monthOptions() {
      return getMonths;
    },

Months.js

import { i18n } from "../../boot/i18n.js";

export const getMonths = () => [
  { id: "January", name: i18n.t("MONTHS.JANUARY") },
  { id: "February", name: i18n.t("MONTHS.FEBRUARY") },
  { id: "March", name: i18n.t("MONTHS.MARCH") },
  { id: "April", name: i18n.t("MONTHS.APRIL") },
  { id: "May", name: i18n.t("MONTHS.MAY") },
  { id: "June", name: i18n.t("MONTHS.JUNE") },
  { id: "July", name: i18n.t("MONTHS.JULY") },
  { id: "August", name: i18n.t("MONTHS.AUGUST") },
  { id: "September", name: i18n.t("MONTHS.SEPTEMBER") },
  { id: "October", name: i18n.t("MONTHS.OCTOBER") },
  { id: "November", name: i18n.t("MONTHS.NOVEMBER") },
  { id: "December", name: i18n.t("MONTHS.DECEMBER") }
];

I've tried so many things, but to no avail.. Does anyone have suggestions? Thanks.

Upvotes: 1

Views: 1062

Answers (2)

mateuscad
mateuscad

Reputation: 11

so i tried like Estus said, but i don't know why didn't work. So, i find another way. I left the translation happens in the component. Like this:

const getMonths = () => [
  { id: "January", name: "MONTHS.JANUARY" },
  { id: "February", name: "MONTHS.FEBRUARY" },
  { id: "March", name: "MONTHS.MARCH" },
  { id: "April", name: "MONTHS.APRIL" },
  { id: "May", name: "MONTHS.MAY" },
  { id: "June", name: "MONTHS.JUNE" },
  { id: "July", name: "MONTHS.JULY" },
  { id: "August", name: "MONTHS.AUGUST" },
  { id: "September", name: "MONTHS.SEPTEMBER" },
  { id: "October", name: "MONTHS.OCTOBER" },
  { id: "November", name: "MONTHS.NOVEMBER" },
  { id: "December", name: "MONTHS.DECEMBER" }
];

And

computed:
monthOptions() {
      return getMonths().map(months => ({
      ...months,
      name: this.$t(months.name)  
      }))
    },

Thanks!

Upvotes: 0

Estus Flask
Estus Flask

Reputation: 222309

That months is defined outside computed property disables the reactivity of t. The array needs to be created inside monthOptions. If it's reused between components, Months.js should export a function that returns an array instead of an array:

export const getMonths = () => [{...}]

Upvotes: 1

Related Questions