How to Use Filters in Vue.js

Today we are going to learn how to use filters in Vue.js. Let’s get started:

Table of Contents

  1. Understanding Filters
  2. Global Filters
  3. Local Filters
  4. More Info

Understanding Filters

Vue.js allows us to define filters that can be used to apply common text formatting. We can use filters globally or locally. The syntax:

// global
Vue.filter('filterName', function(value) {
  return // the data to filter
});

// locally, like methods or mounted
filters: {
  filterName(value) {
    return // the data to filter
  }
}

Filters are usable in two places: mustache interpolations and v-bind expressions.

<!-- in mustaches -->
{{ data | filterName }}

<!-- in v-bind -->
<div v-bind:id="rawId | formatId"></div>

Global Filters

We’ve to define a filter globally before creating the Vue instance:

main.js
import Vue from 'vue'
import App from './App.vue'

Vue.filter('capitalize', function (value) {
  if (!value) return ''
  value = value.toString()
  return value.charAt(0).toUpperCase() + value.slice(1)
})

new Vue({
  render: h => h(App),
}).$mount('#app')
App.vue
<template>
  <div id="app">
    <!-- using `capitalize` filter -->
    <h1>{{ name | capitalize }}</h1>
  </div>
</template>

<script>
export default {
  data() {
    return {
      name: "obydul",
    }
  }
};
</script>

Local Filters

We have to define local filters in the component’s options:

<template>
  <div id="app">
    <!-- using `uppercase` filter -->
    <h1>{{ name | capitalize }}</h1>
  </div>
</template>

<script>
export default {
  data() {
    return {
      name: "obydul",
    }
  },
  filters: {
    capitalize: function (value) {
      if (!value) return ''
      value = value.toString()
      return value.charAt(0).toUpperCase() + value.slice(1)
    }
  }
};
</script>

More Info

We can also pass additional arguments into filters:

 // filtering
{{ data | filterName(arg1, arg2) }}

// make filter
filters: {
  filterName(value, arg1, arg2) {
    return //thing to transform
  }
}

Now, let’s take a look at some examples:

Reverse String:

filters: {
  reverseString: function (value) {
    return value.split("").reverse().join("");
  }
}

Uppercase:

filters: {
  uppercase: function (value) {
    return value.toUpperCase();
  }
}

Filters can be chained:

{{ message | filterA | filterB }}

That’s all. I hope you’ve got some idea about Vue.js filters.


Software Engineer | Ethical Hacker & Cybersecurity...

Md Obydullah is a software engineer and full stack developer specialist at Laravel, Django, Vue.js, Node.js, Android, Linux Server, and Ethichal Hacking.