post-ad

Add Filter In Vue JS

Introduction:

A filter is a straightforward JavaScript function that is used to modify data sent to the browser. Wherever we save the data, filters in Vue.JS merely apply to format; they don’t really alter the data. Only the way the data is displayed to a browser changes; the data itself stays the same. We must create these filters because Vue.JS doesn’t provide them by default. We have two distinct methods to utilize filters with Vue.JS: global filtering and local filtering. While local filters only let us utilize our filters inside the designated component, global filters provide us access to all components.

Get Started:

Step 1: Set up your VUE project.

Goto your desired folder location and run the following command to create a new Vue project.

vue create vue-filter

It will take some time. After creating the project, run the following command to check project is successfully established or not.

npm run serve

Step 2: Register filter definition.

We creating the global filter in this post. Go to the main.js file and add a filter to it. Here, is the syntax.

Vue.filter('filterName', function(value){
  return value;
});

Example:

For example, we just create the ‘dateObject’ filter which will take a value like ’30-05-2022′ and convert it into a javascript Date Object.

In the main.js file,

Vue.filter('dateObject', function(value){
  const [day, month, year] = value.split('-');
  return new Date(+year, month - 1, +day);
});

In this example, the ‘dateObject’  filter accepts the value and does some process for converting the simple string, and finally returns the Date Object.

Step 3: Use a filter in your components.

Simply add the filter by first adding a pipe symbol to your template, then adding the filter’s name. To apply a filter, use the syntax.

{{ text | nameOfFilter }}

Go to your desired component and add a variable to it.

<script>
export default {
  name: 'HelloWorld',
  data: function () {
    return {
      dateText: "30-05-2022", // to be filtered.
    };
  },
}
</script>

Now, filter out variables using a pipe sign in your HTML.

<template>
  <div>
    <h3>{{ dateText | dateObject }}</h3>
  </div>
</template>

Go to http://localhost:8080/  and check your output!

Submit a Comment

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

Subscribe

Select Categories

page-ad