Create a simple time ago component in Vue using Moment.js
https://dev.to/maxwelladapoe/create-a-simple-time-ago-component-in-vue-using-momentjs-3en7
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 yarn yarn 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
}
},
created() {
this.moment = moment;
},
computed:{
convertedDateTime(){
return moment(this.dateTime).fromNow();
}
}
}
</script>
to use it in your project
...
<time-ago :dateTime='new Date()'/>
...
<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
https://dev.to/maxwelladapoe/create-a-simple-time-ago-component-in-vue-using-momentjs-3en7
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 yarn yarn 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
}
},
created() {
this.moment = moment;
},
computed:{
convertedDateTime(){
return moment(this.dateTime).fromNow();
}
}
}
</script>
to use it in your project
...
<time-ago :dateTime='new Date()'/>
...
<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
DEV Community
Create a simple time ago component in Vue using Moment.js
Ever needed a time ago component where you can parse a datetime string and get your date in the...