Filters

Filters in Vue.js are different from the filters in Java EE. In a Vue application, you use filters to format texts in Mustache interpolations or v-bind expressions. A filter is a JavaScript function that takes an expression's value as its first argument. Vue.js provides two types of filter registration—globally with Vue.filter(), and locally with the filters property of a component's options.

In our Messages App, the default date and time format that we used on the message's createdAt property aren't looking good. Let's create a global filter, datetimeto provide a better format.

As a convention, we will put the filter file under the filters directory and name it in this format: ${filterName}.filter.js, similar to the names of the directives. We use Intel.DateTimeFormat to do the formatting. Alternatively, you might want to use libraries such as date-fns or moment.js, which provide much richer APIs.

Let's have a look at the filters/datetime.filter.js file:

const formatter = new Intl.DateTimeFormat('en-US', {
year: 'numeric', month: 'long', week: 'long', day: 'numeric',
hour: 'numeric', minute: 'numeric', second: 'numeric'
});
Vue.filter('datetime', function(value) {
if (!value) return '';
return formatter.format(value);
});

To enable this filter, we need to import it into index.html as well. Let's have a look at the index.html file:

... 
<script type="module">
...
import './filters/datetime.filter.js';
...
</script>

To use this filter, we append it to the end of item.createdAt, separated with the pipe.

Let's have a look at the components/MessageListItem.js file:

export default {
...
template: `<li>{{ item.text }} - {{ item.createdAt | datetime }}
<button @click="deleteClicked">X</button></li>`,
...
};

You can chain multiple filters like this—{{ expression | filterA | filterB }}. The result of expression will be the first argument of filterA, and the result of filterA result will be passed to filterB as its first argument.

You can also provide additional arguments to a filter. For example, when using the date-fns library, we can support date and time formatting with different patterns with only a few lines of code. We can add a second parameter to the filter function for passing desired patterns, as follows:

Vue.filter('datetime', function(value, pattern) {
...
});

And here is how to specify a pattern when using the filter:

{{ item.createdAt | datetime('MM/DD/YYYY') }} 

The MM/DD/YYYY string will be passed in as the second argument. You can also define the format pattern as a variable and pass it to the filter.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.226.240