Filters

In this section, we're going to investigate filters; you may have come across filters before in frameworks such as Angular (Pipes). Perhaps we want to create a filter that allows us to format a date in a readable format (DD/MM/YYYY). Let's create a playground project to investigate this further:

# Create a new Vue project
$ vue init webpack-simple vue-filters

# Navigate to directory
$ cd vue-filters

# Install dependencies
$ npm install

# Run application
$ npm run dev

If we had some test people and used the v-for directive to display them on screen, we'd get the following result:

To obtain the result shown in the preceding screenshot, where we display our test people with the appropriate data through the v-for directive, we would have to add the following code:

<template>
<div id="app">
<ul>
<li v-for="person in people" v-bind:key="person.id">
{{person.name}} {{person.dob}}
</li>
</ul>
</div>
</template>

<script>
export default {
name: 'app',
data() {
return {
people: [
{
id: 1,
name: 'Paul',
dob: new Date(2000, 5, 29),
},
{
id: 2,
name: 'Terry',
dob: new Date(1994, 10, 25),
},
{
id: 3,
name: 'Alex',
dob: new Date(1973, 4, 15),
},
{
id: 4,
name: 'Deborah',
dob: new Date(1954, 2, 5),
},
],
};
},
};
</script>

We could do the work of converting the date ourselves, but where possible it's always worth looking to see if there is a trusted third-party component that can do the same thing. We'll be using moment (https://momentjs.com) to do this.

Let's install moment for our project:

$ npm install moment --save

We can then add it to our App.vue:

<script>
import moment from 'moment';

export default {
// Omitted
}
</script>