How to Use Filters in a Vue.js App for Beginners

Filters are actually a feature provided by Vue.js that lets you apply common text formatting to your data. Filters do NOT change the data itself but rather change the output to the browser by returning a filtered version of that data.

Most VueJS developers are extremely familiar with computed properties. They’re a great way to design more readable code and declutter your template.

However, in certain cases, there’s a better solution that can make even more reusable code: VueJS Filters. In this tutorial, you’ll learn how to use custom Vue.js filters inside the Vue component.

How to Use Filters in a Vue.js App

Let’s suppose you’ve created a custom filter (uppercase) that transforms the text into uppercase. It can be either a global or local filter.

Now, here is how we can use filters: either in mustache interpolations Hey {{ username | capitalize }} OR in a v-bind expression (notice the pipe in both of them).

<!--  With  mustache  interpolations  -->
<h1>{{  article.title  |  uppercase }}</h1>

<!--  With  v-bind  expression  -->
<title-component  :title="article.title  |  uppercase"  />

You can define a filter as global (available in all components) or local (only in the component it is defined in). Here is how you would define a local filter:

export  default  {
  filters:  {
    capitalize:  function(value)  {
      if  (!value)  {
        return  "";
      }
      value  =  value.toString();
      return  value.charAt(0).toUpperCase()  +  value.slice(1);
    }
  }
};

Defining a Global Filter in Vue.js

Create a separate file where you store your filters. For small projects, I usually stored them in a folder named helpers.

import  Vue  from  "vue";

Vue.filter("capitalize",  function(value)  {
  if  (!value)  {
    return  "";
  }
  value  =  value.toString();
  return  value.charAt(0).toUpperCase()  +  value.slice(1);
});

Then, just import this file into your Vue entry point (usually: main.js).

import  "@/helpers/filters";

Chaining Filters

It’s also possible to apply multiple filters to a single value.

This is pretty intuitive. All we have to do is insert another “pipe” after our first filter, and then declare our second filter. Something like this.

<h1>{{ name | upper | lower }}</h1>

Now, both text transformations are applied to our original data.

Passing Arguments to Filters

Since filters are JavaScript functions, they accept the value to be transformed as the first parameter. You can also pass as many arguments as you need according to the needs of your application.

<h1>{{ message | filterA('arg1', arg2) }}</h1>

Just as we can pass several arguments, it is possible to link several filters, for that we just need to use the pipe symbol (|) and through several transforming filters, we obtain a single value.

Originally published by Suresh Ramani at Techvblogs

#vuejs #vue #javascript 

How to Use Filters in a Vue.js App for Beginners
1.45 GEEK