Vue.js – Using Filters In Templates

vuejs introduction and installation

When you make tea, what do you do with the tea leaves? When making lemonade, what do we do with the seeds? Or what does our water purifier do with the water? They all filter. They filter out the unnecessary things and return just what is needed. We have a kind of similar feature in vue. If you’ve used angular before, you must know about filters. Let us have a look at filters.

What is a Vue Filter?

Vue filters are nothing but simple functions. These functions receive a value as input and they return another value as output. Vue filters are often used in operating upon data received from external APIs. it has a very simple syntax. FIlters are often used with mustache tags. Syntax – {{ value | filter_name }} Notice the | sign between the value and the filter_name.

Creating and Defining a Filter

Filters can be defined globally or locally, They need to be added to another attribute called filter in the default export.

vue js home layout

This was just a local filter, it cannot be used in another component. If we want to create a filter that can be accessed from anywhere we would have to pass it to Vue. To do this we would simply modify our main.js like this.

vue js filter function

This needs to be written before creating the vue instance. Now the filter will be globally accessible across all vue files and components.

Filters inside JavaScript

This is a piece of information that is not officially available, but it exists and works. We have only seen filters being used in the HTML templates, You may often find the need to filter some data from within the JavaScript part of your component. In order to do this, we can follow this simple trick.

Just call this.$options.filter_name(input_value). This will return the same output that one would get from the filters used in templates. Needless to say, filter_name should be replaced with the name of the defined filter and input_value should contain the input value upon which the operation is to be performed.

Conclusion

Vue filters are extremely useful in filtering and cleansing values in templates. They can be defined globally or locally. These filters can also be called from within the JavaScript part of the application. I am sure you have a clear idea about filters. If you are still confused, feel free to drop a comment and I’ll be there for you.

Author: Rishabh Kandari

Rishabh Kandari is a Tech Enthusiast and a Web Developer. He shares his knowledge by writing blogs on TheITStuff. He also specialises in inappropriate humour an sarcasm.