vue3 定时器-定义全局方法 vue+ts
1.创建ts文件
路径:src/utils/timer.ts
完整代码:
import { onUnmounted } from 'vue'type TimerCallback = (...args: any[]) => voidexport function useGlobalTimer() {const timers: Map<number, NodeJS.Timeout> = new Map()// 创建定时器const setInterval = (callback: TimerCallback,delay: number,...args: any[]): number => {const timerId = window.setInterval(() => callback(...args), delay)timers.set(timerId, timerId)return timerId}// 清除单个定时器const clearInterval = (timerId: number) => {window.clearInterval(timerId)timers.delete(timerId)}// 清除所有定时器const clearAll = () => {timers.forEach((timer) => {window.clearInterval(timer)})timers.clear()}// 组件卸载时自动清理onUnmounted(clearAll)return {setInterval,clearInterval,clearAll}
}
2.挂载到全局属性
路径:src/main.ts
完整代码:
import { createApp } from 'vue'
import App from './App.vue'
import { useGlobalTimer } from './utils/timer'const app = createApp(App)// 挂载到全局属性
app.config.globalProperties.$timer = useGlobalTimer()app.mount('#app')
3.使用方式:
引入全局方法:
import {getCurrentInstance } from 'vue'
const { proxy } = getCurrentInstance()!
使用:
创建定时器:
proxy!.$timer.setInterval(() => { // 需要定时循环的内容 // }, 时间);
清除定时器:
proxy!.$timer.clearInterval(timerId)
完整代码:
<template></template><script setup lang="ts" name="index">
import {ref, onMounted, onUnmounted, getCurrentInstance} from 'vue';
const {proxy} = getCurrentInstance()!
let timerId: numberonMounted(() => {
//创建定时器timerId = proxy!.$timer.setInterval(() => {//循环内容}, //循环时间);
});
onUnmounted(() => {
//清除定时器proxy!.$timer.clearInterval(timerId)
})
</script>
<style scoped lang="scss"></style>