vue-timers
Simple mixin to manage timers or intervals for Vue.js
Installation
1.1 Use CDN
<script src="https://cdn.jsdelivr.net/npm/vue-timers/dist/vue-timers.umd.js"></script>
1.2 Install from package manager
npm install vue-timers
yarn add vue-timers
2.1. Global import
import Vue from 'vue'
import VueTimers from 'vue-timers'
Vue.use(VueTimers)
2.2. Or use mixin for the specific component
import {mixin as VueTimers} from 'vue-timers'
export default {
mixins: [VueTimers]
}
2.3. Nuxt plugins
nuxt.config.js
:
export default {
plugins: [
{ src: '~/plugins/vue-timers', mode: 'client' }
]
}
plugins/vue-timers.js
:
import Vue from 'vue'
import VueTimers from 'vue-timers'
Vue.use(VueTimers)
What it does?
It creates timer instances in components and slightly reduces boilerplate code with their handling.
See the following code
export default {
methods: {
log () {
console.log('Hello world')
}
},
created () {
this.$options.interval = setInterval(this.log, 1000)
console.log(this.$options.interval !== null)
},
beforeDestroy () {
clearInterval(this.$options.interval)
}
}
It's ugly, isn't it? So let's try to fix this :)
Same code with vue-timers
:
export default {
timers: {
log: { time: 1000, autostart: true }
},
methods: {
log () {
console.log('Hello world')
}
}
}
Configuration
Timer object
{
name: String,
callback: Function/String,
autostart: Boolean,
repeat: Boolean,
immediate: Boolean,
time: Number
isSwitchTab: Boolean
}
Changing timer duration
this.timers.log.time = 2000
NOTE: you should restart timer to apply changes
Component methods
this.$timer.start('log')
this.$timer.stop('log')
isRunning property
this.timers.log.isRunning
Events
TimerComponent.vue
import { timer } from 'vue-timers'
export default {
timers: [
timer('log', 1000)
],
methods: {
log () {
console.log('It works!')
}
}
}
App.vue
<template>
<timer-component
@timer-start:log="timerStarted"
@timer-stop:log="timerStopped"
@timer-tick:log="timerTicked"
/>
</template>
3 ways of timers declaration
Object notation
export default {
timers: {
log: { time: 1000, ...options }
}
}
Array notation
export default {
timers: [
{ name: 'log', time: 1000, ...options }
]
}
Helper function
import { timer } from 'vue-timers'
export default {
timers: [
timer('log', 1000, { ...options })
]
}
Author
Anton Kosykh
License
MIT