How to use Vue.js filters to format data?

To use Vue.js filters to format data, you can follow these steps:

  1. Define a filter function: In your Vue.js component, you need to define the filters property and add a filter function. This filter function takes an input value and returns the formatted output. For example, let's create a filter to format a number as currency:
filters: { formatCurrency(value) { return '$' + value.toFixed(2); } }
  1. Use the filter in your template: Once you have defined the filter function, you can use it in your template to format data. To apply a filter, you use the pipe (|) symbol followed by the filter name. For example, to format a number as currency, you would use {{ myNumber | formatCurrency }}.

Here's an example of using the formatCurrency filter in a Vue component:

<template> <div> <p>{{ originalPrice }}</p> <p>{{ originalPrice | formatCurrency }}</p> </div> </template> <script> export default { data() { return { originalPrice: 10.5 }; }, filters: { formatCurrency(value) { return '$' + value.toFixed(2); } } }; </script>

In the above example, the originalPrice data property is initially set to 10.5. In the template, the first <p> tag will display the original value (10.5), while the second <p> tag will display the formatted value ('$10.50') using the formatCurrency filter.

By using Vue.js filters, you can easily format data in your templates without modifying the source data itself.