当前位置: 首页 > news >正文

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>

相关文章:

  • IDC智能机房整体解决方案
  • 第三方检测:软件渗透测试
  • 分类预测 | Matlab基于AOA-VMD-BiLSTM故障诊断分类预测
  • HubSpot推出与ChatGPT的深度集成引发兴奋与担忧
  • 消息队列生产问题解决方案全攻略
  • 安宝特方案丨XRSOP人员作业标准化管理平台:AR智慧点检验收套件
  • 学习时困了怎么办
  • 安宝特案例丨寻医不再长途跋涉?Vuzix再次以AR技术智能驱动远程医疗
  • linux cgroup内存/io/cpu/网络使用总结
  • 人工智能--安全大模型训练计划:基于Fine-tuning + LLM Agent
  • Linux下如何使用Curl进行网络请求
  • 单片机bootloader(APP的自我复制)
  • Cursor 使用分享
  • ​小学五年级的语言来解释符号​
  • 鸿蒙Next仓颉语言开发实战教程:店铺详情页
  • 快速使用 Flutter 的 Dialog 和 AlertDialog
  • SpringBoot请求限流(RateLimiter)
  • Python开发基础手语识别(基础框架版)
  • 什么是Ansible Jinja2
  • Ansible+Zabbix-agent2快速实现对多主机监控
  • 建筑网站知乎/软件开发工程师
  • 美女做基网站/襄阳网站seo
  • 保密和档案网站建设方案/网站流量数据分析
  • 常州平台网站建设/seo优化搜索推广
  • 做网站 用 云主机/教育培训网站模板
  • 网站开发的成果/昆明seo案例