Filters in Vue.js

Filters are an interesting way to deal with data rendering in Vue but are only useful in a small amount of cases. The first thing to understand about filters is that they aren’t replacements for methods, computed values, or watchers, because filters don’t transform the data, just the output that the user sees.

{{ name | uppercase }}

The filters lowercase and capitalize can be used in a similar manner.

Custom Filters

You can create your own filters as well. We can use filters locally or globally, but it’s worth mentioning that if you declare a Vue filter globally it should come before the Vue instance. In both cases, we would pass the value in as a parameter.

global and local filter syntax

Here’s a small example, with a tip calculator:

Chaining Filters

Filters can also be chained. Keep in mind if you’re going to chain filters: ordering matters. The first filter will be applied first, the second will be applied to the completed first, and so on.

We can also pass additional arguments into filters like so:

Conclusion

Now, you might think, based on the name, that filters would be great for forms when we want to show only some bits of data and not others. However, filters need to rerun on every single update, so if you have something like an input that updates every time you type, it’s not very performant. Better to use computed for something like this as it's less overhead. The results will be cached based on their dependencies and won't be rerun on every update. Computed properties will only be reevaluated when those dependencies change, but can also handle complex logic. This makes them excellent candidates for filtering information based on input. There are, however, circumstances where you do need to update based on changes in time, and for these instances, better to use a method.