A quick greeting example
<template>
<p>Hello {{ firstName }}!</p>
</template>
<script>
export default {
data() {
return {
firstName: ''
}
}
}
</script>
If you run this code, the output will look like this:
Hello !
And that does not look good. Let create a simple filter so that if "firstName" is empty, we print "World" instead. Let's change the code so it looks like this:
<template>
<p>Hello {{ firstName | fallback }}!</p>
</template>
<script>
export default {
data() {
return {
firstName: ''
}
},
filters: {
fallback: function(firstName) {
return firstName ? firstName : 'World'
}
}
}
</script>
If you run this command, the output will look like this:
Hello World!
As you can see, applying filters are really easy. The filters objects can contain a lot of different filters. They accept one value (the value before the pipe/|) and they can return the value with the applied filter. Since Vue.js is so awesome, you can also access the components data and methods too!
A better example
In this example I'm going to show you how to truncate text using a Vue.js filter.
<template>
<p>{{ lorem | truncate }}</p>
</template>
<script>
export default {
data() {
return {
lorem: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam nibh mauris, euismod sed pulvinar id, aliquam eu turpis. Donec in rutrum mauris.'
}
},
filters: {
truncate: function(text) {
return text.substring(0, 10)
}
}
}
</script>
If you run the code in this example, you will see something like this:
Lorem ipsu
But what if you want to have a dynamic limit? Change the example above to make it look like this:
<template>
<p>{{ lorem | truncate(15) }}</p>
</template>
<script>
export default {
data() {
return {
lorem: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam nibh mauris, euismod sed pulvinar id, aliquam eu turpis. Donec in rutrum mauris.'
}
},
filters: {
truncate: function(text, limit) {
return text.substring(0, limit)
}
}
}
</script>
If you run the code in this example, you will see something like this:
Lorem ipsum dol
What else can I use Vue.js filters for?
There are several things you can use filters for like capitalizing, lowercasing an e-mail address, adding prefixed to prices and so much more.
Other Vue.js tutorials
-A short introduction to Vue.js watchers
-Introduction to Vue.js props