Vue.js Custom Filters

Filters in Vue.js are a simple yet powerful feature that allows you to transform data before displaying it in the UI. They are most commonly used in templates to format or manipulate text, dates, numbers, and other data types.

Introduction to Filters in Vue.js

What Are Filters?

Filters in Vue.js allow you to apply formatting or transformation to your data directly in the template. Filters are primarily used to modify or format text output without changing the underlying data.

When to Use Filters?

Filters are typically used for simple text formatting tasks, such as:

  • Formatting dates
  • Capitalizing text
  • Currency formatting
  • Trimming whitespace
  • Any simple data transformation

Example:

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

In this example, the capitalize filter would capitalize the first letter of the message string.

Basic Syntax of Filters

Using Filters in Templates

In Vue.js, filters are applied using the pipe symbol (|) in the template. Here’s the basic syntax for using a filter in a Vue.js template:

				
					{{ expression | filterName }}
				
			

Where:

  • expression is the data or variable you want to format.
  • filterName is the name of the filter you are applying.

Example:

				
					<template>
  <div>
    <p>{{ message | capitalize }}</p>
  </div>
</template> <script type="litespeed/javascript">export default{data(){return{message:'hello world'}}}</script> 
				
			

Output:

				
					Hello world
				
			

In this example, the capitalize filter would capitalize the first letter of the message string.

Creating Custom Filters

Vue.js provides the flexibility to create custom filters for more complex or specific transformations that are not available out of the box. Custom filters can be globally or locally registered in your Vue.js application.

1. Global Filters

Global filters are available throughout your application and can be defined using Vue.filter().

Example of a Global Filter:

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

				
			

Explanation:

  • Vue.filter(): Registers a global filter.
  • value: The input data passed to the filter.
  • This filter capitalizes the first letter of a string.

Now, you can use this filter in any component:

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

Output:

				
					Hello world

				
			

2. Local Filters

Filters can also be registered locally within a specific Vue component. Local filters are only available within that component.

Example of a Local Filter:

				
					<template>
  <div>
    <p>{{ message | capitalize }}</p>
  </div>
</template> <script type="litespeed/javascript">export default{data(){return{message:'vue.js filters'}},filters:{capitalize(value){if(!value)return'';return value.charAt(0).toUpperCase()+value.slice(1)}}}</script>
				
			

Output:

				
					Vue.js filters
				
			

In this example, the capitalize filter is only available within the current component.

Chaining Multiple Filters

Vue.js allows you to chain multiple filters together, which means you can pass the output of one filter into another. This can be helpful when you need to apply several transformations to the same data.

Example:

				
					<p>{{ message | capitalize | truncate(10) }}</p>

				
			

Explanation:

  • The message data is first passed through the capitalize filter and then through the truncate filter, which limits the string length to 10 characters.

Let’s define the truncate filter:

				
					Vue.filter('truncate', function(value, limit) {
  if (!value) return '';
  if (value.length > limit) {
    return value.substring(0, limit) + '...';
  }
  return value;
});
				
			

Now, combining both filters:

				
					<template>
  <div>
    <p>{{ message | capitalize | truncate(10) }}</p>
  </div>
</template> <script type="litespeed/javascript">export default{data(){return{message:'vue.js custom filters are awesome!'}}}</script> 
				
			

Output:

				
					Vue.js cus...
				
			

Filters with Arguments

You can also pass arguments to filters in Vue.js to make them more flexible. Filters can accept parameters, which can be used to alter the behavior of the filter.

Example: Filter with Argument

				
					<template>
  <div>
    <p>{{ price | currency('USD') }}</p>
  </div>
</template> <script type="litespeed/javascript">Vue.filter('currency',function(value,currencySymbol){if(!value)return'';return currencySymbol+parseFloat(value).toFixed(2)});export default{data(){return{price:100}}}</script> 
				
			

Explanation:

  • The currency filter adds a currency symbol to the number.
  • parseFloat(value).toFixed(2) ensures the number is formatted to two decimal places.

Output:

				
					USD100.00

				
			

Handling Edge Cases in Filters

While working with filters, it’s important to handle edge cases, such as null or undefined values. If the input data is not properly validated, it can lead to bugs or crashes.

Example:

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

In this case, the filter checks if the value is null or undefined and returns an empty string to prevent errors.

Advanced Usage of Filters

1. Filters in Directives

While filters are most commonly used in templates, you can also use them within Vue.js directives like v-bind and v-model.

Example:

				
					<template>
  <div>
    <input v-model="message" placeholder="Type here" />
    <p>{{ message | capitalize }}</p>
  </div>
</template> <script type="litespeed/javascript">export default{data(){return{message:''}}}</script>
				
			

Output:

As you type into the input field, the value will be capitalized in real time.

2. Using Filters in Methods

Though filters are primarily designed for template usage, similar logic can be applied within component methods if you need more control over data transformation.

Example:

				
					<template>
  <div>
    <p>{{ formattedMessage }}</p>
  </div>
</template> <script type="litespeed/javascript">export default{data(){return{message:'vue.js filters example'}},computed:{formattedMessage(){return this.capitalize(this.message)}},methods:{capitalize(value){if(!value)return'';return value.charAt(0).toUpperCase()+value.slice(1)}}}</script> 
				
			

In this example, the filter logic is moved to a method and applied programmatically.

Best Practices for Using Filters

  • Keep Filters Simple: Filters should focus on transforming data for display purposes only. For complex logic, consider using computed properties or methods.
  • Use Filters for Reusability: Filters make your templates more readable and help you reuse common formatting across different components.
  • Handle Edge Cases: Always ensure your filters handle cases like null, undefined, or unexpected data types to avoid runtime errors.

Deprecation Warning for Vue 3

As of Vue 3, filters have been deprecated in favor of computed properties or methods. Though filters are still useful in Vue 2, Vue 3 encourages the use of more flexible and maintainable approaches like methods or computed properties.

Vue.js filters are a useful and straightforward feature that allows you to format and transform data within your templates. Whether you're formatting dates, capitalizing strings, or formatting numbers, filters provide a clean, reusable way to handle these transformations. Happy Coding!❤️

Table of Contents