/

Vue.js Filters: Formatting and Transforming Data in Templates

Vue.js Filters: Formatting and Transforming Data in Templates

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:

1
2
3
4
5
6
7
8
9
10
11
12
13
<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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<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:

1
{{ name | fallback | capitalize }}

Beyond basic usage, filters can also accept parameters:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<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.