What are filters in vue.js

In Vue.js, filters are functions that can be used to format or transform data within the template. They provide a way to apply common text formatting or data manipulation without having to write complex logic directly in the template. Filters can be applied to data bindings in the template using the {{ expression | filterName }} syntax.

Here are some key details about filters in Vue.js:

1. Syntax

The syntax for using filters in templates is {{ expression | filterName }}, where expression is the data or variable to be formatted, and filterName is the name of the filter.

2. Filter Definition

Filters are defined in the filters option of a Vue component. The filters option is an object where each key is a filter name, and the value is a function that performs the transformation.

filters: {
  capitalize(value) {
    if (!value) return '';
    return value.charAt(0).toUpperCase() + value.slice(1);
  }
}

3. Filter Application

Filters are applied to data in the template using the | pipe character.

<p>{{ message | capitalize }}</p>

4. Chaining Filters

Multiple filters can be chained together, and they are applied from left to right.

<p>{{ date | formatDate | toUpperCase }}</p>

5. Filter Arguments

Filters can accept additional arguments, which can be provided within parentheses.

<p>{{ price | formatCurrency('USD') }}</p>

Here, formatCurrency is a filter that takes a currency code as an argument.

6. Global Filters

Vue allows you to register global filters that can be used across multiple components.

Vue.filter('reverse', function(value) {
  return value.split('').reverse().join('');
});

Once registered globally, the filter can be used in any component template.

7. Limitations

Starting from Vue.js 2.0, filters are not recommended for complex transformations or data manipulation. For more complex scenarios, it's advised to use computed properties or methods.

Example

Here's a simple example of using a filter to capitalize the first letter of a string:

<template>
  <div>
    <p>{{ message | capitalize }}</p>
  </div>
</template>

<script>
export default {
  data() {
    return {
      message: 'hello world'
    };
  },
  filters: {
    capitalize(value) {
      if (!value) return '';
      return value.charAt(0).toUpperCase() + value.slice(1);
    }
  }
};
</script>

In this example, the capitalize filter is used to capitalize the first letter of the message property when displayed in the template.