Use VueJS filters with MomentJS

MomentJS is a library that I love to manage the dates and you can put to work with #Vue using the filters, I will explain how to combine them.

The first thing is to add the references to #MomentJS and Vue in our page, besides creating a file named filters.js to store all filters functions.

<script src="https://momentjs.com/downloads/moment-with-locales.js"></ script> <script src = "https://vuejs.org/js/vue.js"> </ script> <script src = "filters.js"> </ script>

Creating Filter

Using the function Vue.filter() and passing the name of the filter as the first parameter and the function as a second. My example the function receives the date as parameter and inside I write the definition of our function that is using the MomentJS library, using as parameters the date and a format “YYYYMMDD”, this creates an instance of MomentJS that contains the method fromNow () that returns us the time from the date we have passed until today.

Vue.filter ('timeago', function (date) { return moment (date, "YYYYMMDD"). fromNow () })

Using the filter

We can use our filter when we do the binding of a property, using the mode “mustache” {{ourprop} and add a pipe “|” after the name of the property.

<td> {{game.gamelog | timeago}} </ td>

You can see the complete example here: https://jsbin.com/yejuyen/edit?html,js,output