Filter in Vue.js

With Vue.js, you can register your filters in two different ways: Globally and Locally. The former gives you access to your filter across all your components, unlike the latter which only allows you to use your filter inside the component it was defined in.

Filters are simple JavaScript functions, they take the value to be transformed as the first parameter, but you can also pass in as many other arguments as you will need to return the formatted version of that value.

1). Global Filters:

<div id="app">
  <span>{{ 351.99 | toUSD }}</span>
</div>

Vue.filter('toUSD', function (value) {
    return `$${value}`;
});

2). Local Filters:

new Vue({
    el: '#app',

    data: {
        name: 'vue.js'
    },

    filters: {
       // Filter definitions
        Upper(value) {
            return value.toUpperCase();
        }
    }
});

// USAGE
<div id="app">
  <span>{{ name | Upper }}</span>
</div>

As you can see in the example above, Local Filters are stored within the Vue component as functions inside the “filters” property. You can register as many as you want:

filters: {
       Upper(value) {
             return value.toUpperCase();
       },
       Lower(value) {
           return value. toLowerCase();
       },
   }
  • Additional Arguments:

Vue.filter('readMore', function (text, length, suffix) {
    return text.substring(0, length) + suffix;
});

new Vue({
    el: '#app',

    data: {
        text: 'Hey This is an example of filter in vue js,you can learn more about vue.js from the code hubs.'
    }
});

// USAGE
<div id="app">
  <span>{{ text | readMore(10, '...') }}</span>
</div>

In this example, we created a filter with the name “readMore” which will limit the length of a string to a given number of characters and will also append a suffix of your choice to it. Vue.js passes the value to be filtered as the first param text and lengthsuffix as the second and third parameter.

3). Chaining Filters:

One of my favorite things about Filters is the ability to chain them using the pipe ( | ) symbol and run a single value through a series of transformers. Let’s use the example of price value again; we want to limit it to two numbers after a comma and add the dollar sign to it.

Although we can achieve this using one single filter we might also want to use toUSD filter on its own. Separating and chaining filters, in this case, is the way to go:

Vue.filter('toFixed', function (price, limit) {
    return price.toFixed(limit);
});

Vue.filter('toUSD', function (price) {
    return `$${price}`;
});

new Vue({
    el: '#app',

    data: {
        price: 435.333
    }
});

 

<div id="app">
  <span>{{ price | toFixed(2) | toUSD }}</span>
</div>

Submit a Comment

Your email address will not be published. Required fields are marked *

Footer Logo

Subscribe

Select Categories