This tutorial is out of date and no longer maintained.
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 front end. 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.
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.
We will be reproducing a few of them in the examples below.
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.
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>
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>
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>
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();
},
}
....
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
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>
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:
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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 very useful Vue.js filters including the ones above. Head over there to see how you can install and use them.
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.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
This textbox defaults to using Markdown to format your answer.
You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!