Vue Filters
Using Filters to Format Data in Vue.js Templates:
Vue.js there is a filter feature that enable you to process data and give it a suitable format to be displayed on a template. Filters are easy modifiers that can be utilised both inside double curly braces {{}} and in v-bind expressions.
They are a good tool for restructuring text, dates, numerical data and other sort of information before final rendering in the UI.
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.