案例:获取当前时间

<script lang="ts">

import { defineComponent, onMounted, onBeforeUnmount, ref } from 'vue'

export default defineComponent({
  setup() {
    let dataTime = ref('')
    
    //定义 timer 初始值及类型
    let timer: NodeJS.Timer | null = null

    // 当前时间
    const getNowTime = () => {
      const now = new Date()
      const year = now.getFullYear()
      const month = now.getMonth() >= 9 ? now.getMonth() + 1 : `0${now.getMonth() + 1}`
      const date = now.getDate() >= 10 ? now.getDate() : `0${now.getDate()}`
      const hour = now.getHours() >= 10 ? now.getHours() : `0${now.getHours()}`
      const minutes = now.getMinutes() >= 10 ? now.getMinutes() : `0${now.getMinutes()}`
      const seconds = now.getSeconds() >= 10 ? now.getSeconds() : `0${now.getSeconds()}`
      dataTime.value = `${year}年${month}月${date}日 ${hour}:${minutes}:${seconds}`
    }

    onMounted(() => {
      getNowTime()
      timer = setInterval(() => {
        getNowTime()
      }, 1000)
    })

    onBeforeUnmount(() => {
      // 清理定时器要处理 timer 的类型
      clearInterval(Number(timer))
    })

    return {
      dataTime
    }
  }
})
</script>

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐