Ever needed a time ago component where you can parse a datetime string and get your date in the format like 10 days ago , a year ago etc.? Well you could create that easily in vue.js using moment.js.
Let's dive straight into it.
- Install moment.js using npm
npm install moment --save
or with yarnyarn add moment
- Create a new component. You can name it TimeAgo.vue
- In your component
//TimeAgo.js <template> <span>{{convertedDateTime}}</span> </template> <script> import moment from 'moment' export default { name: "TimeAgo", props:{ dateTime:{ required:true } }, computed:{ convertedDateTime(){ return moment(this.dateTime).fromNow(); } } } </script>
to use it in your project
<template> ... <time-ago :dateTime='new Date()'/> ... </template> <script> import TimeAgo from "@/components/TimeAgo"; export default { ... components: { TimeAgo } ... } </script>
and thats it. This should work in vue 2 and vue 3 without any issues. if you need to extend it you can see the moment.js docs
Top comments (0)