vue-i18n : how to use inside vue instance filter

9k views Asked by At

I want to use a filter to perform translations.
Problem is that 'this' doesn't point to my vue instance inside my filter function.

This is what I currently have.

inside my template I have this:

  <p>{{ parking.status | translate }} </p>

inside my component I have this:

 new Vue({ ...
 filters: {
      translate: function(value, vue) {
          return this.$i18n.t('MLAA-47');
 } 

The error I get is that this == undefined.
How do i point it to my vue instance inside my filter function ?

3

There are 3 answers

0
JP. Aulet On BEST ANSWER

As points @vitaly-mosin in the comment in that answer explains that you couldn't use this inside the filter functions.

filters are primarily designed for text transformation purposes. For more complex data transforms in other directives, you should use Computed properties instead.

I had the same issue and I resolved moving the translation with $i18n to a computed method, like:

Inside your template, instead of this:

 <p>{{ parking.status | translate }} </p>

Change it to:

<p>{{ translateStatus(parking.status) }} </p>

And in the methods:

methods: {
    translateStatus (status) {
        return this.$t(status)
    }
},

I guess that you have a dynamic status (not returning always: 'MLAA-47') and you should assert that you have translations for all of them. It worked for me!

Hope it helps to you too

0
Alonad On

We can import file exporting i18n instance like this

import i18n from '@/i18n.js'

And use it like this

i18n.t('your.message')
0
Mike Mat On

I am not sure if this is a good idea, but so far it is doing what I want.

Define the filters like

// the instance.vue will be set on App.vue
export const instance = {
  vue: null
};

// little helper
const t = (key) => instance.vue?.$t?.(key);

export default {
  filter: (v) => v + t('somekey')
}

Then in App.vue (or whatever it is you use), do

import {instance} from '@/filters'

export default {
  mounted() {
    instance.vue = this; // set the instance here