Skip to content

Instantly share code, notes, and snippets.

@silasrm
Last active July 7, 2020 12:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save silasrm/3c6ca21b58376ee832d063988fd53f2d to your computer and use it in GitHub Desktop.
Save silasrm/3c6ca21b58376ee832d063988fd53f2d to your computer and use it in GitHub Desktop.
A vue-timeago (https://github.com/egoist/vue-timeago/) version using luxon
// directives/TimeAgo.js
import DateTime from 'luxon/src/datetime.js';
/**
* Need Luxon https://moment.github.io/luxon/
* @usage import Timeago from '../directives/TimeAgo';
Vue.use(Timeago, {locale: 'pt-BR'}); // or Vue.use(Timeago);
* @param opts
*/
export const createTimeago = (opts = {}) => {
const name = opts.name || 'Timeago'
return {
name,
props: {
datetime: {
required: true
},
format: {
default: 'y-MM-dd HH:mm:ss'
},
title: {
type: [String, Boolean]
},
locale: {
type: String,
default: 'en'
},
autoUpdate: {
type: [Number, Boolean]
},
converter: {
type: Function
},
converterOptions: {
type: Object
}
},
data () {
return {
timeago: this.getTimeago()
}
},
computed: {
localeName () {
return this.locale || this.$timeago.locale
}
},
mounted () {
this.startUpdater()
},
beforeDestroy () {
this.stopUpdater()
},
render (h) {
return h(
'time',
{
attrs: {
datetime: new Date(this.datetime),
title:
typeof this.title === 'string'
? this.title
: this.title === false
? null
: this.timeago
}
},
[this.timeago]
)
},
methods: {
getTimeago (datetime) {
return DateTime.fromFormat(datetime || this.datetime, this.format)
.setLocale(this.$timeago.locale || this.locale)
.toRelative({days: 1});
},
convert (datetime) {
this.timeago = this.getTimeago(datetime)
},
startUpdater () {
if (this.autoUpdate) {
const autoUpdate = this.autoUpdate === true ? 60 : this.autoUpdate
this.updater = setInterval(() => {
this.convert()
}, autoUpdate * 1000)
}
},
stopUpdater () {
if (this.updater) {
clearInterval(this.updater)
this.updater = null
}
}
},
watch: {
autoUpdate (newValue) {
this.stopUpdater()
if (newValue) {
this.startUpdater()
}
},
datetime () {
this.convert()
},
localeName () {
this.convert()
},
converter () {
this.convert()
},
converterOptions: {
handler () {
this.convert()
},
deep: true
}
}
}
}
export const install = (Vue, opts) => {
if (Vue.prototype.$timeago) {
return
}
if (process.env.NODE_ENV === 'development' && !Vue.observable) {
console.warn(`[timeago] Vue 2.6 or above is recommended.`)
}
const $timeago = opts === undefined ? {} : {
locale: opts.locale,
};
Vue.prototype.$timeago = Vue.observable
? Vue.observable($timeago)
: new Vue({data: $timeago})
const Component = createTimeago(opts)
Vue.component(Component.name, Component)
}
export default install;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment