Creating custom filters in Vue.js (tutorial)

in Code Write a comment

Learn the basics of creating and applying Vue.js filters.

You can create custom filters to format text, dates etc. You can apply filters in v-bind expressions and moustache brackets.

Creating custom local filters

Let’s create a filter that will transform the text into uppercase. We can create a new local filter inside our component.

filters: {
  uppercase: function (value) {
    if (!value) return ''
    return value.toString().toUpperCase();
  }
}

You can then use this filter in two places:

<!-- mustache interpolation -->
{{ message | uppercase }}

<!-- v-bind expression -->
<p v-bind:text="message | uppercase"></p>

Creating global filters in Vue.js

Let’s make our uppercase filter global. To make it available in other components we need to define it before creating the Vue instance.

Vue.filter('uppercase', function (value) {
  if (!value) return ''
  return value.toString().toUpperCase();
})

new Vue({
  // ...
})

Filters can also be chained:

{{ message | uppercase | truncate }}

If you find this post useful, please let me know in the comments below. 
Cheers,
Renat Galyamov

Want to share this with your friends?
👉renatello.com/vue-js-filters

PS: Make sure you check other Vue.js tutorials, e.g. vue.js scroll to top on route change, using jQuery with Vue.js (pros and cons).

Write a Comment

Comment