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:
- The template interpolation expression.
- The
v-bind
expression.
<!-- 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:
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:
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:
<p> {{ amount | round(3) }} </p>
And in the filter, we add a new parameter like so:
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.
<p> {{ amount | round(3) | currency('$') }} </p>
This way, we could get an even refined value.
filters: {
round(value, decimalPlace = 2){
if(!value) return '';
return (typeof value === 'number')? value.toFixed(decimalPlace ) : value;
},
currency(amount, symbol){
return `${symbol} ${amount}`
}
}