requestAnimationFrame的用法,实现定时刷新的功能
<script> export default { data () { return { time: 0, // 时间标志位 interval: 10000, // 定时任务执行时间间隔 timer: null } }, methods: { intervalTimer () { let currTime = new Date().getTime() if(currTime - this.time > this.interval || this.time === 0) { this.$EventBus.$emit('timerAttach', {}) this.time = new Date().getTime() } this.timer = requestAnimationFrame(this.intervalTimer) // 返回值是一个long整数,请求ID,是回调列表中唯一的标识,你可以传这个值给window.cancelAnimationFrame()以取消回调函数 } }, destroyed () { // 组件销毁,关闭定时执行 cancelAnimationFrame(this.timer) }, created() { // 开启定时任务 this.intervalTimer() // 可以在任何你需要定时执行的地方都监听eventBus的timerAttach事件,比如我们的消息通知需要一直定时执行,所以我们加在app的created方法中。 const that = this this.$EventBus.$on('timerAttach', () => { API.getStatusUsingGET({ id: that.statusid }).then(res => { console.log(res) }).catch(err => { console.log('error' + err) }) }) } } </script>