Contact Information

KodeBlog

We're Available 24/ 7. Drop us an email.

VueJS Filters

Vue Filters are used to format data to be displayed without altering the underlying original data. For example, you can use a filter to format a number to currency and append the currency symbol to it without modifying the original data that is used for formatting.

In this lesson, we will explain how filters work and how you can use them in your Vue applications when necessary.

Topics to be covered

We will cover the following topics in this lesson

Lesson Prerequisites

For you to successfully complete this lesson, you should have the following requirements

  • NodeJS - this is mainly needed for development purposes only. You need NPM which comes with Node to work with tools like Vue CLI
  • Web Browser - a web browser can be used as an alternative to executing JavaScript files that we will be working with.
  • Visual Studio Code - we will be using it as the code editor. It comes with a built-in terminal that will allow us to easily execute JavaScript code from within the text editor. You can also use any code editor that you prefer.
  • JavaScript Basics - this is an added advantage and not mandatory. We will explain every piece of code covered in these lessons.
  • HTML & CSS Basics - this is an added advantage. Vue works on the HTML elements to manipulate them. The styling is done using CSS so you must be familiar with the basics

Lesson Practical Examples Project Setup

This is a practical based lesson. For you to successfully work out the examples given in this lesson, you will need to setup the following directories and files

Create a new directory called vue-components

Open the directory vue-components in Visual Studio Code or your favorite code editor

Create the following files inside your project folder.

  • index.html - this is the file that will contain our application source code

The following visualizes our project setup

vue-components
-index.html

How to Define Filters in Vue

The Vue instance has a filters initialization parameter that we can use to define filters for our applications. Filters must be defined as functions that return a value. By default, a filter function has the value to be formatted as an argument. You do not need to explicitly pass the value to be formatted to the filter.

The following code shows how to define a filter function in Vue

let vm  = new Vue({
    el: '#root',
    data: {
        data: 5000,
    },
    filters: {
        filterFunction: function(value){
            return 'Formatted value';
        }
    }
});

HERE,

  • filters: {...} we define the function filterFunction: function(value){...} that has one parameter value. Within the function filterFunction we apply formatting rules then return the formatted value.

The filter can now be used like so

{{ data | filterFunction}}

HERE,

  • {{ data | filterFunction}} we output the value of data and apply the filter filterFunction using the pipe | symbol. Vue JS will call the filter function with the value of data then displayed what has been returned from the function instead of the value of data directly.

Vue Filter Example

Let's now create a simple application that defines a data member amount that will be a numeric value. We will then create a filter function that will format the amount using commas so that it is easy for human beings to read it.

Open the file index.html and add the following code

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>Vue Filters</title>
        <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    </head>
    <body>
        <div id="root">
            <p>Filtered Amount: {{amount | formatNumber}}</p>
            <p>Original Amount: {{amount}}</p>
        </div>
        <script type="text/javascript">
            let vm  = new Vue({
                el: '#root',
                data: {
                    amount: 5000,
                },
                filters: {
                    formatNumber: function(value){
                        return value.toLocaleString();
                    }
                }
            });
        </script>
    </body>
</html>

HERE,

  • data: {...} defines a data member amount that is assigned the value 5000.
  • filters: {...} defines a filter function formatNumber that returns a human easy to read number.
  • <p>Filtered Amount: {{amount | formatNumber}}</p> outputs the value of amount using the filter formatNumber
  • <p>Original Amount: {{amount}}</p> prints the value of amount without the filter formatNumber

Open the file index.html in the web browser

You should be able to get the following results

Filtered Amount: 5,000
Original Amount: 5000

Notice how the first value has a comma separate to make it easy to read but the second parameter has the original numeric value and it has not been modified.

Vue Filter Arguments

In the above example, we called the filter function formatNumber without explicitly passing in any parameter. In this section, we will modify our filter to accept a second argument that will display the currency symbol at the beginning of the number.

Modify the filter function as follows

filters: {
    formatNumber: function(value,currency){
        return currency + value.toLocaleString();
    }
}

HERE,

  • filters: {...} defines an additional parameter currency in our filter function. return currency + value.toLocaleString(); appends the value of currency to the beginning of value

In the HTML section, modify the output filtered code like so

<p>Filtered Amount: {{amount | formatNumber('$')}}</p>

HERE,

  • formatNumber('$') calls the filter function with the string argument $. Notice how we defined a function with two parameters function(value,currency){...} but when calling it we are passing in only the second parameter. This is because the first argument value is automatically passed in for us by Vue

Run the above code produces the following results

Filtered Amount: $5,000
Original Amount: 5000

Vue Filter Scope

Filters can have either a global or local scope. Global filters are accessible to all running Vue instances and you do not need to define the global filter explicitly on the instance for it to access it. Local filters are only available within the particular scope where they have been defined.

Global Filters

Global filters are declared directly on the Vue object before initialization. The following code shows how to define a filter on a global scope

Vue.filter('formatCurrency', function(value,currency){
    return currency + value.toLocaleString();
});

let vm  = new Vue({
    el: '#root',
    data: {
        amount: 5000,
    }
});

HERE,

  • Vue.filter('formatCurrency', function(value,currency){...} defines a filter formatCurrency on the Vue object. This gives our filter a global scope.
  • let vm = new Vue({...}); defines a Vue instance without explicitly defining the filter formatCurrency

The above global filter can now be used like so

<p>Filtered Amount: {{amount | formatCurrency('$')}}</p>

The above code produces the following results

Filtered Amount: $5,000

Local Filters

Local filters are only accessible to the Vue instance where they are defined. For example, if you create two instances vm1 and vm2 and define a filter directly on the instance vm1, trying to access it within the element that is attached to the instance vm2 does not work.

The following example defines a local filter on the instance vm that takes a post title then converts it to a URL friendly value

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>Vue Filters</title>
        <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    </head>
    <body>
        <div id="root">
            <p>SEO Title: {{title | seoTitle}}</p>
            <p>Human Title: {{title}}</p>
        </div>
        <script type="text/javascript">
            let vm  = new Vue({
                el: '#root',
                data: {
                    title: 'VueJS Tutorial',
                },
                filters: {
                    seoTitle: function(value){
                        return value.replace(' ','-');
                    }
                }
            });
        </script>
    </body>
</html>

HERE,

  • filters: {...} defines a local filter on the instance vm
  • <p>SEO Title: {{title | seoTitle}}</p> filters the value of title using the filter seoTitle

Open the file local.html in the web browser

You should be able to get the following results

SEO Title: VueJS-Tutorial
Human Title: VueJS Tutorial

Notice how the space has been replaced with a dash - in the filtered output

Chaining Filters

Sometimes you may need to apply more than one filter on a value. Chaining allows you to do that. You basically separate the multiple filters using pipe | symbols like so

{{value | filter1 | filter2}}

We will modify the SEO title example and create a filter function that will convert all letters to lower case then replace the dashes so that we can convert the human title to a SEO friendly one.

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>Vue Filters</title>
        <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    </head>
    <body>
        <div id="root">
            <p>SEO Title: {{title | lower | seoTitle}}</p>
            <p>Human Title: {{title}}</p>
        </div>
        <script type="text/javascript">
            let vm  = new Vue({
                el: '#root',
                data: {
                    title: 'VueJS Tutorial',
                },
                filters: {
                    lower: function(value){
                        return value.toLowerCase();
                    },
                    seoTitle: function(value){
                        return value.replace(' ','-');
                    }
                }
            });
        </script>
    </body>
</html>

HERE,

  • filters: {...} defines two filters lower and seoTitle
  • <p>SEO Title: {{title | lower | seoTitle}}</p> chains the filters lower and seoTitle to format the value of title

Executing the above code produced the following results

SEO Title: vuejs-tutorial
Human Title: VueJS Tutorial

Summary

Filters are used to format data before it is displayed. Filters do not modify the original data. They receive the original data, transform it then return the result for output. Global filters are accessible to all instances of Vue defined while local filters are only accessible within the instance where they are declared. Multiple filters can be chained using the pipe | symbol.

Author: Rodrick Kazembe

Rodrick is a developer who works on Desktop, Web and Mobile Applications. He is familiar with Python, Java, JavaScript, C++, C#, Kotlin, PHP, Python and the list goes on. Rodrick enjoys sharing knowledge especially when it comes to technology.

VueJS Events

Leave A Reply