Filter alternatives in vuejs

About three months ago I started using filters in my vue-template files. I created a whole formatter-library in our private NPM-repo with the aim to use the functions in there as filters. I had also started promoting this strategy (well discussed beforehand) with my colleauges. And then I found out that …

In vue 3 filters will no longer work. My colleagues, who have experience back to vue 1, tell me the vue-team has tried to get rid of filters before. They hope Evan and his team will change their minds for vue 3.1. However, if they don’t, there are decent alternatives.

So what are filters? They are a way to format input in a vue-template. The syntax looks like this:

<div>{{number | euro}}</div>

The ‘euro’ filter can format the number to include a euro sign and perhaps format the number in an EU-locally appropriate way.

I like this syntax because reading from left to write I first get the value and the variable the value is coming from and only then what it will be formatted as. Since the formatting is usually an (important) afterthought and rarely relevant for bug fixing, it makes sense to have it last.

There are basically two ways to circumvent filters for this purpose:

  • Methods
  • Computed properties

Methods

Using methods in templates feels off. It’s a rarely used method in the documentation and for obvious reasons: it means that the method gets called again and again, without caching. However, under the hood filters and methods are precisely the same thing, so it’s not an argument against methods as a replacement for filters. The syntax is pretty obvious:

<div>{{euro(number)}}</div>

Again: the euro method will transform the number into a string starting with a euro-sign. Just like a filter, but the syntax is just slightly less obvious on first sight. You will first notice that you’re dealing with euro’s and only then with the actual variable.

Computed properties

My template files are full of computed properties. From transformed data to simple references to my vuex-store. However, in order to use them to transform my data to something humanly legible I would have to do something like this (assuming my number isn’t coming from some long list of data):

computed: {
    number(){return 5},
    euroNumber(){ return this.euro(this.number) }
}
<template>
    <div>{{euroNumber}}</div>
</template>

This means that the underlying ‘number’ property is hidden behind the euroNumber property, which necessitates an extra step when debugging. However, this approach does mean that the resulting ‘euroNumber’ variable is cached, which can speed up the application, especially when there is a lot of data.

Conclusion

I will miss filters. When we transition over from vue2 to vue3, I guess we will mostly use methods instead.

Geef een reactie

Deze site gebruikt Akismet om spam te verminderen. Bekijk hoe je reactie-gegevens worden verwerkt.