Using Filters In Templates in Vue js

Today’s topic is about Using Filters In Templates in Vue js. 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.

Using-Filters-In-Templates-in-Vue-js

Using Filters In Templates in Vue js

Before we start talking about using filters in Vue js JavaScript, we need to know about Filters in Vue first.

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

vue js home layout

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

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.

Get real time updates directly on you device, subscribe now.

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More