Open In App

Adding Filters in VueJS

A Filter is a simple JavaScript function which is used  to change the output of a data to the browser. Filters in Vue.JS don’t change the data directly wherever we store them, it only applies formatting to our data. The data remains the same only the output of a data to a browser is changed. Vue.JS doesn’t give these filters by default, so we have to make these filters. With Vue.JS , we can use filters in two different ways i.e. Global filter and Local filter. Global filter provides access all the components while Local filter only allows us to use our filter inside the component it was defined.

Prerequisites: Basics of Vue.JS



Approach: Below all the steps are described order wise to create Filters in Vue.JS .

Vue.filter('uppercase', function(value));
Vue.filter('uppercase', function (value) {
  return value.toUpperCase();
});
{{ title | filtername }}

Below is a sample program to illustrate the above approach:



Global Filter: The scope of global filter is throughout our Vue app.

Example 1: In the below program, we will reverse a given string using global filter.

main.js




// GLOBAL FILTER
// In this example, we are 
// creating a filter which
// reverses the given string
import Vue from "vue";
  
// Importing App.vue
import App from "./App.vue";
  
// Declaration
Vue.filter("reverseString", function (value) {
    return value.split("").reverse().join("");
});
  
new Vue({
    render: (h) => h(App)
}).$mount("#app");

App.vue




<!--Template--> 
<template>
  <div id="app">
      
    <!--Applying filter-->
    <h1>{{ name | reverseString }}</h1>
  </div>
</template>
  
<script>
export default {
  data: function () {
    return {
      name: "GEEKSFORGEEKS",
    };
  },
};
</script>

Output

Local Filter: The scope of local filter is within a component.

Example 2: In the below program, we will change given string to uppercase using local filter.

App.vue




<!-- Local filter in VueJS -->
<!-- Template -->
<template>
  <div>
    
    <!-- Applying Uppercase filter -->
    <h1>{{ name| uppercase }}</h1>
  </div>
</template>
  
<!-- Filter defined locally -->
<script>
export default {
  data: function() {
    return {
      name: "geeksforgeeks"
    };
  },
  filters: {
    uppercase: function(value) {
      return value.toUpperCase();
    }
  }
};
</script>

Output


Article Tags :