How to Use Filters in Vue.js

Last modified on March 13, 2020 1 min read

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.

Author

Hey, I'm Md Obydullah. I build open-source projects and write on Laravel, Linux server, modern JavaScript and more on web development.

Follow

Leave a Reply

Your email address will not be published. Required fields are marked *