Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

vue-i18n : how to use inside vue instance filter

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 ?

like image 614
hannes neukermans Avatar asked Jan 25 '26 22:01

hannes neukermans


1 Answers

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

like image 136
JP. Aulet Avatar answered Jan 28 '26 22:01

JP. Aulet