[Vuejs]-Translation in data in Vue

0👍

this.$t isn’t available when data gets created, so at the point it is null, just like your error says.

I’d create a method to handle this issue:

data() {
  return {
    mounted: false,
    noteRules: [
      v => !!v || this.translate("requiredChangesDescription")
    ],
  },
},
mounted() {
  this.mounted = true;
},
methods: {
  translate(s) {
    if (this.isMounted) return this.$t(s);
    return "";
  }
}

If you need this behaviour in several files, consider creating a mixin instead.

0👍

You can use computed props for these,

computed: {
  noteRules() {
    return [v => !!v || this.$t('requiredChangesDescription')]
  }
}

EDIT:

If you’re handling really large translations files, you can spread the objects.

So for instance, your translation files look like this,

translations.js

export const Home = {
  title: 'Home Page Title',
  description: 'Home Page description'
};

export const SomeComponent = {
  title: 'Component Title'
};

export const CompX = {
  title: 'ComponentX Title'
};

export const CompY = {
  title: 'ComponentY Title'
};

You can selectively build your computed props to use only the translations you want,

computed: {
  copyText () {
    return { CompX: { ...this.$t('CompX') }, CompY: { ...this.$t('CompY') } }
  }
}

And use the copyText in your template for the bindings.

You’ll need the CompX, CompY wrappers in your computed only if you have repeating keys (Example: title in our code above) in your translations.js file.

If you have distinct keys, you can just do this;

computed: {
  copyText () {
    return { ...this.$t('CompX'), ...this.$t('CompY') }
  }
}

Leave a comment