How to Create Filters in Vue.js with Examples

Rachid Laasri
๐Ÿ‘๏ธ 11,269 views
๐Ÿ’ฌ comments

Similar to AngularJS, Vue.js has its way of transforming data and applying filters to it, but you must keep in mind that filters don't transform the original data, they only change the output and return a filtered version of it. Filters can be useful in a lot of different situations like keeping your API responses as clean as possible and handling the formatting of your data on your frontend. They can also be efficient in cases where you want to avoid repetition and concatenation by encapsulating all that logic behind reusable code blocks.

I hope this small introduction got you excited to learn more about Filters. How you can create and use them and couple more things you will discover going through the article. HERE WE GO!

Vue.js Default Filters

If this isnโ€™t your first time reading about Vue.js filters then you know that the older versions shipped with built-in filters, but they got removed from Vue 2.0 and this is Evan You โ€™s (the creator of Vue.js)โ€™ reasoning behind that:

Built-in filters can be useful, but they lack the flexibility of pure JavaScript. When a built-in function doesn't suit your needs, you either end up re-implementing something similar (and shipping both in your final code, where the built-in becomes useless, dead code) or have to wait for Vue to update them and release a new version.

With that in mind, be careful reading or watching old tutorials. Here is a full list of the old default filters in case you want to learn more about them: Filters - vue.js.

Spoiler Alert: We will be reproducing few of them in the examples below

Defining and Using Filters

With Vue, 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.

Global Filters

Here is what a Global filter looks like:

// In this example, we will register a global filter
// which will add the dollar sign in front of the price:

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

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

PS: The filter definition must always be above the main Vue instance, or you will get a โ€œFailed to resolve filter: toUSDโ€ error.

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

new Vue({
    el: '#app',

     data: {
        price: 351.99
    }
});

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

See it in action

Local Filters

Local filters are registered to a Vue component scope. The following illustrates how they are created:

// In this example, we are creating a filter 
// That turns the string you give it to upper-case.

// DECLARATION
new Vue({
    el: '#app',

    data: {
        name: 'scotch.io'
    },

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

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

See it in action

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

As we mentioned in the introduction of this article, Filters can take as many arguments as you need:


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

new Vue({
    el: '#app',

    data: {
        text: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit. Non ab modi repellendus labore facere, fugiat ipsam quae accusantium commodi voluptas nesciunt dolor similique ipsum accusamus earum eligendi suscipit laborum quod.'
    }
});

// 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 length, suffix as the second and third parameter.

See it in action: Edit fiddle - JSFiddle

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>

Check it out in action

Examples

If you made it to this part of the article, congratulations! That was everything you needed to know about Vue.js filters, but it is always a good idea to go through few examples:

  • Convert a JavaScript value to a JSON string:
Vue.filter('json', function (value) {
    return JSON.stringify(value);
});

new Vue({
    el: '#app',

    data: {
        user: {
            username: 'johndoe',
            email: 'john@example.com',
            countryCode: 'U.K.'
        }
    }
});
<div id="app">
  <span>{{ user | json }}</span>
</div>

Edit fiddle - JSFiddle

  • Extracting a list of property values from an array of objects:
Vue.filter('pluck', function (objects, key) {
    return objects.map(function(object) { 
        return object[key];
    });
});

new Vue({
    el: '#app',

    data: {
        users: [
        {
            "id": 4,
            "first_name": "Eve",
            "last_name": "Holt"
        },
        {
            "id": 5,
            "first_name": "Charles",
            "last_name": "Morris"
        },
        {
            "id": 6,
            "first_name": "Tracey",
            "last_name": "Ramos"
        }
        ]
    }
});
<div id="app">
  <span>{{ users | pluck('last_name') }}</span>
</div>

Edit fiddle - JSFiddle

  • Return the element at the given index:
Vue.filter('at', function (value, index) {
    return value[index];
});

new Vue({
    el: '#app',

    data: {
        videos: ['Zi_XLOBDo_Y', 'sOnqjkJTMaA', 'sOnqjkJTMaA']
    }
});
<div id="app">
  <span>{{ videos | at(1) }}</span>
</div>

Edit fiddle - JSFiddle

  • Return the minimum value in a given list:
Vue.filter('min', function (values) {
    return Math.min(...values);
});

new Vue({
    el: '#app',

    data: {
        ages: [23, 19, 45, 12, 32]
    }
});
<div id="app">
  <span>{{ ages | min }}</span>
</div>

Edit fiddle - JSFiddle

  • Shuffle a list of elements:
Vue.filter('shuffle', function (values) {
    for (var i = values.length - 1; i > 0; i--) {
        var j = Math.floor(Math.random() * (i + 1));
        var temp = values[i];
        values[i] = values[j];
        values[j] = temp;
    }
    return values;
});

new Vue({
    el: '#app',

    data: {
        cards: ['Lahire', 'Judith', 'Lancelot', 'Alexandre']
    }
});
<div id="app">
  <span>{{ cards | shuffle }}</span>
</div>

Edit fiddle - JSFiddle

  • Return the first element of an array:
Vue.filter('first', function (values) {
    if(Array.isArray(values)) {
        return values[0];
    }
    return values;
});

new Vue({
    el: '#app',

    data: {
        consoles: ['PlayStation', 'Nintendo DS', 'Xbox', 'Atari']
    }
});
<div id="app">
  <span>{{ consoles | first }}</span>
</div>

Edit fiddle - JSFiddle

  • Return the last element of an array:
Vue.filter('last', function (values) {
    if(Array.isArray(values)) {
        return values[values.length - 1];
    }
    return values;
});

new Vue({
    el: '#app',

    data: {
        consoles: ['PlayStation', 'Nintendo DS', 'Xbox', 'Atari']
    }
});
<div id="app">
  <span>{{ consoles | last }}</span>
</div>

Edit fiddle - JSFiddle

  • Return a copy of the array without the given elements:
Vue.filter('without', function (values, exclude) {
    return values.filter(function(element) {
        return !exclude.includes(element);
    });
});

new Vue({
    el: '#app',

    data: {
        unpaidInvoices: ['#1001', '#1002', '#1003', '#1004']
    }
});
<div id="app">
  <span>{{ unpaidInvoices | without('#1003') }}</span>
</div>

Edit fiddle - JSFiddle

  • Remove duplicated elements in an array:
Vue.filter('unique', function (values, unique) {
    return values.filter(function(element, index, self) {
        return index == self.indexOf(element);
    });
});

new Vue({
    el: '#app',

    data: {
        recentViewedPosts: [13, 43, 23, 13, 43, 3, 98, 42, 65]
    }
});
<div id="app">
  <span>{{ recentViewedPosts | unique }}</span>
</div>

Edit fiddle - JSFiddle

  • Prepend text to a string:
Vue.filter('prepend', function (string, prepend) {
    return `${string}${prepend}`;
});

new Vue({
    el: '#app',

    data: {
        greeting: 'Hello'
    }
});
<div id="app">
  <span>{{ greeting | prepend(' World!') }}</span>
</div>

Edit fiddle - JSFiddle

  • Repeat a string n times:
Vue.filter('repeat', function (string, times) {
    return string.repeat(times);
});

new Vue({
    el: '#app',

    data: {
        greeting: 'Hello'
    }
});
<div id="app">
  <span>{{ greeting | repeat(3) }}</span>
</div>

Edit fiddle - JSFiddle

If you are interested in these filters and you want to use them in your project GitHub - wy-ei/vue-filter: A collection of Vue.js filter. offers a set of a very useful Vue.js filters including the ones above. Head over there to see how you can install and use them.

Conclusion

I hope you learned something from this post and you now know how to create and use filters and most importantly you can now refactor your code and clean it a bit with filters.

Stay tuned for more Vue.js tutorials and see you soon!

Rachid Laasri

4 posts

Yet another web developer.