vue-plugin-timers
A Vue.JS plugin/mixin that helps set timeouts and heartbeats in your Vue components
The Problem - Creating Heartbeats
Say we create a vue.js component
export default {
data: {
minutes: new Date().getMinutes()
}
}
What if we want minutes to update along with the user's clock
when this component is open.
export default {
get minutes() {
return new Date().getMinutes()
}
}
But, unfortunately this does not work.
Reason ?
new Date()
or Date.now()
type of objects are not reactive
We get their value once, but it doesn't update every minutes/second or so
Solution - Use timers
With vue-plugin-timers
we can create a timers
option in Vue
components. Timers run a method in your component every x
seconds
(where you can choose x).
How to Use ?
We can activate timers in two ways
-
As a Component Mixin in any component
import { VueTimersMixin } from 'vue-plugin-timers'
export default {
mixins: [VueTimersMixin],
...,
timers: { ... }
}
-
As a global Vue Plugin if you want to use in multiple components
import Vue from 'vue'
import VueTimers from 'vue-plugin-timers'
Vue.use(VueTimers)
You can use timers
property in all components now
export default {
...,
timers: { ... }
}
You can define timers in 2 ways -
- As a
timers
property in component options (in single-file-component export or inside Vue.extend()) - If using
vue-class-component
, then there are @Timer
decorators 🎉
Usage: timers
component option
export default {
data: {
time: new Date().toTimeString()
},
methods: {
updateTime() {this.time = new Date().toTimeString()}
},
timers: {
updateMinutes: {
interval: 30000,
repeat: true
}
}
}
Usage: @Timer
decorator
⚠️ IMPORTANT: This needs vue-class-component
to be installed,
(or vue-property-decorator
)
import Vue from 'vue'
import Component from 'vue-class-component'
import { Timer } from 'vue-plugin-timer'
@Component
class TimerComponent extends Vue {
count = 0
@Timer({ interval: 200 })
incr() {
this.count++
}
}
The @Timer
decorator takes all the same options as the
timers
component options hashes do. Except the method name, because
you are decorating the method itself and so it is not needed
NOTE: The umd builds do NOT have the decorator,
as decorators are something we usually use when building with
Vue CLI using Babel and/or Typescript