Vue Filters

Example:

                                  
<div id="app">
  <p>{{ message | capitalize }}</p>
  <p>{{ date | formatDate }}</p>
</div>

<script>
new Vue({
  el: '#app',
  data: {
    message: 'hello, vue!',
    date: new Date()
  },
  filters: {
    capitalize(value) {
      if (!value) return '';
      return value.charAt(0).toUpperCase() + value.slice(1);
    },
    formatDate(value) {
      if (!value) return '';
      return new Date(value).toLocaleDateString('en-US', { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' });
    }
  }
});
</script>

                                  
                                

Here is the Vue component having two <p> element that will display messages and dates respectively.

We filter(capitalize and formatDate) such inputs before displaying it in the UI.


Creating Custom Filters:

In addition to using built-in filters, you can create custom filters to apply custom formatting logic to your data.

Custom filters are considered to be as functions in the filters collection of your component and as globally using Vue. filter.

Example:

                                  
<div id="app">
  <p>{{ message | customFilter }}</p>
</div>

<script>
Vue.filter('customFilter', function(value) {
  if (!value) return '';
  // Custom formatting logic
  return value.toUpperCase();
});

new Vue({
  el: '#app',
  data: {
    message: 'hello, vue!'
  }
});
</script>

                                  
                                

The given example selectively filters an item named customFilter by utilizing Vue. filter. The function filter accepts a value which serves as an input and applies customized formatting logic to it (in this case, the process must be just changing the value to uppercase letters).

We begin by creating this custom filter in our template and then nodding the formatted message data into the UI.


Custom filters allow you to wrap commonly used formatting routine as a function and refactor data through the component.

Johannesburg Standard (js) app, therefore, simplifying reusability and maintenance of the code.