Vue.js filters provide a convenient way to format and transform dynamic data used in a template. Filters do not modify component data but only affect the output of the template.
For example, consider a scenario where we want to print a name:
<template>
<p>Hi {{ name }}!</p>
</template>
<script>
export default {
data() {
return {
name: 'Flavio'
}
}
}
</script>
But what if we want to check if name
has a value and print “there” if it doesn’t? Filters come to the rescue:
<template>
<p>Hi {{ name | fallback }}!</p>
</template>
<script>
export default {
data() {
return {
name: 'Flavio'
}
},
filters: {
fallback: function (name) {
return name ? name : 'there'
}
}
}
</script>
In the above example, the fallback
filter is applied using the syntax {{ name | fallback }}
. Filters can be chained as well, allowing us to apply multiple filters one after another:
{{ name | fallback | capitalize }}
Beyond basic usage, filters can also accept parameters:
<template>
<p>Hello {{ name | prepend('Dr.') }}</p>
</template>
<script>
export default {
data() {
return {
name: 'House'
}
},
filters: {
prepend: (name, prefix) => {
return `${prefix} ${name}`
}
}
}
</script>
In the above example, the prepend
filter accepts a prefix
parameter, which allows us to add a prefix to the name.
For more advanced filtering capabilities, you can explore the vue2-filters
package from npm. It offers a wide range of pre-made filters, including options like capitalize
, uppercase
, lowercase
, placeholder
, truncate
, currency
, pluralize
, and more.