Vue3.x中自定义时钟钩子函数(TypeScript语法)

  钩子函数的运用能使我们的代码更加简洁且易于维护,那么在Vue3.x中钩子函数的编写方式是怎样的呢?
  下面,我以一个点击获取当前时间的例子来记录钩子函数的编写过程。

创建hooks目录

  一般情况下,我们都会在src文件目录下创建一个hooks文件夹,专门用来存放我们自定义的钩子函数。在这里插入图片描述

创建并编写钩子函数

  创建好了目录,我们就可以创建钩子函数了。
  我们在创建钩子函数的时候习惯性在命名前面加上use,没有为什么,仅仅是大多数程序员的习惯而已。例如我们要写的函数是获取当前时间,那我就将其命名为useNowTime.ts(这里我用的是TypeScript语法,所以是ts文件,但是其中的代码js同样兼容)。

// 引入ref依赖
import {
    
     ref } from "vue";

// 创建变量储存时间并初始化
const nowTime = ref("00:00:00");
// 创建变量传递方法
const getNowTime = () => {
    
    
    const now = new Date();
    // 时间字符串格式化(如果是一位数则前置0)
    const hour = now.getHours() < 10 ? `0${
      
      now.getHours()}` : now.getHours();
    const minu =
        now.getMinutes() < 10 ? `0${
      
      now.getMinutes()}` : now.getMinutes();
    const sec =
        now.getSeconds() < 10 ? `0${
      
      now.getSeconds()}` : now.getSeconds();
    // 拼接时间并储存在变量nowTime中
    nowTime.value = `${
      
      hour}:${
      
      minu}:${
      
      sec}`;
    // 实现时钟自走效果
    setTimeout(getNowTime, 1000);
};

// 暴露钩子函数,方便其他模块调用
export {
    
     nowTime, getNowTime }

使用钩子函数

  简单地在App.vue中使用一下上面编写的钩子函数:

<template>
  <div>{
    
    {
    
     nowTime }}</div>
  <button @click="getNowTime">点击获取当前时间</button>
</template>

<script lang="ts">
import {
    
     nowTime, getNowTime } from "./hooks/useNowTime";

export default {
    
    
  name: "App",
  setup() {
    
    
    return {
    
    
      nowTime,
      getNowTime,
    };
  },
};
</script>

<style>
</style>

在这里插入图片描述
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_43592084/article/details/109824037