Skip to content

Instantly share code, notes, and snippets.

@bluven
Created November 29, 2018 09:46
Show Gist options
  • Save bluven/4cca5606906492bcdea7a64e2dbbd7b8 to your computer and use it in GitHub Desktop.
Save bluven/4cca5606906492bcdea7a64e2dbbd7b8 to your computer and use it in GitHub Desktop.
一个简化interval管理的vue-mixin
/**
* interval structure {
* name: 'syncStatus' // 需要管理的方法,必须返回boolean值
* time: 5000 必须填
* autoStart: true // 组件加载时是否自动启动 默认 false
* onFinish: 'loadBigIps' // 结束时要执行的动作,可以不设置
* }
*/
export default {
data() {
if (this.$options.intervals && this.$options.intervals.length > 0) {
return {
intervals: this.$options.intervals.reduce((intervals, i) => {
intervals[i.name] = Object.assign({}, i)
return intervals
}, {})
}
} else {
return {}
}
},
computed: {
hasIntervals() {
return this.$options.intervals && this.$options.intervals.length > 0
}
},
created() {
if (!this.hasIntervals) return
const vm = this
vm.$intervals = {
start(name) {
const originFunc = vm[name]
const interval = vm.intervals[name]
const clear = function() {
clearInterval(interval.instance)
if (interval.onFinish) {
vm[interval.onFinish].apply(vm)
}
}
interval.instance = setInterval(() => {
const result = originFunc.apply(vm)
if (typeof result === 'boolean' && result) {
clear()
} else {
// result is promise
result.then(ok => {
if (ok) {
clear()
}
})
}
}, interval.time)
},
stop(name) {
const interval = vm.intervals[name]
if (interval.instance) {
clearInterval(interval.instance)
}
}
}
},
mounted() {
if (!this.hasIntervals) return
this.$options.intervals.forEach(interval => {
if (interval.autoStart) {
this.$intervals.start(interval.name)
}
})
},
beforeDestroy() {
if (!this.hasIntervals) return
this.$options.intervals.forEach(interval => {
this.$intervals.stop(interval.name)
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment