How to use Vue.js filters inside the Vue instance

in Code Write a comment

In this tutorial, you’ll learn how to use custom Vue.js filters inside the Vue component.

Let’s suppose you’ve created a custom filter (uppercase) that transforms the text into uppercase. It can be either global or local filter more on that here.

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

Now you can use it inside the template like so.

{{ message | uppercase }}

This is how most of the developers use them. But what if you want to re-use those filters inside the Vue instance.

You can do that too! There’s no need to create additional methods.


Hi, I'm Renat 👋

 


All you need to do is call the vm.$options object wherever you need to use your previously created filters.

this.$options.filters.uppercase(this.message)

That’s it! You can now apply your filters inside the Vue instance.

Example:

// ...
methods: {
  resetForm () {
    // ...
    this.message = this.$options.filters.uppercase(this.message)
  }
}

If you find this post useful, please let me know and share your favourite filters in the comments below..

Cheers,
Renat Galyamov

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

PS: You can also check how to get the first item in Vue.js arrayhow to add a class to body tag in Vue.jsHow to hide uncompiled mustache {{ code }} in Vue.js and other Vue.js tutorials.

A collection of UI components for
Bootstrap 4/5 and Vue.js

Get now

Write a Comment

Comment