# Using Filters in Vue

Filters in Vue.js are helper functions that can be used to quickly format text in a component's template.

## How to use filter functions

Filters can be used in two places in a template:

1. The template interpolation expression.
2. The `v-bind` expression.

```html
<!-- usage in interpolations -->
<p> {{ amount | round }} </p>

<!-- in v-bind -->
<input type="text" v-bind:value="amount | round" disabled/>

```

To use a filter, we simply add the name of the function to the end of the expression which is signified by the "pipe" symbol. (`|`).

According to[ Linfo.org](http://www.linfo.org/pipes.html "All about pipes")

> _A pipe is a form of redirection that is used to send the output of one program to another program for further processing._

So in this case, the value from the first expression is now sent via the "pipe" to the filter function to return the new value.

## Registering Filter functions

They can either be registered globally for use in multiple components or locally in a single component.

### Registering a filter globally

We can set the filter function for use in multiple components by setting it using `Vue.filter()` just before initialization:

```javascript
import Vue from 'vue';

Vue.filter('round', function(value){
	if(!value) return '';
    return (typeof value === 'number')? value.toFixed(2) : value;
})
```

Now the filter can be used in any component.

### Registering a filter locally

To use a filter locally, simply add it to the `filters` object as a method:

```javascript
filters: {
	round(value){
   		if(!value) return '';
    	return (typeof value === 'number')? value.toFixed(2) : value;
    }
}
```

The value from the first expression is always the first argument, It's possible to pass arguments to a filter function.

## Passing arguments to a filter function

If we wanted to tweak the outcome of the filter, say to modify how many decimal places the `round` function returns.

In the template, we simply add the arguments like a normal function:

```html
<p> {{ amount | round(3) }} </p>
```

And in the filter, we add a new parameter like so:

```javascript
filters: {
	round(value, decimalPlace = 2){
   		if(!value) return '';
    	return (typeof value === 'number')? value.toFixed(decimalPlace ) : value;
    }
}
```

## Chaining filters

We can pass the value to another filter too after the first modified value is being returned.

```html
<p> {{ amount | round(3) | currency('$') }} </p>
```

This way, we could get an even refined value.

```javascript
filters: {
	round(value, decimalPlace = 2){
   		if(!value) return '';
    	return (typeof value === 'number')? value.toFixed(decimalPlace ) : value;
    },
    currency(amount, symbol){
    	return `${symbol} ${amount}`
    }
}
```
