- 按钮文字默认显示"开始倒计时"
 - 当点击按钮时,显示正在倒计时(倒计时数字)
 - 倒计时结束按钮显示"开始倒计时"
 
倒计时逻辑 Hooks 函数
hooks/useCountDown.js
            
            
              javascript
              
              
            
          
          /**
 * hooks函数:函数是用于封装和复用组件逻辑的一种机制
 * 定义:Hooks 是一种在不使用类组件的情况下复用状态逻辑的方法
 * 目的:将组件中的逻辑抽取出来,形成可复用的函数
 * 特点:遵循 Composition API 的思想,使逻辑组织更加灵活
 * 命名规范:通常以 use 开头命名 Hook 函数,如 useCounter、useFetch 等
 */
import {ref, watch} from "vue";
// 封装并导出倒计时函数
export function useCountDown(num = 60) {
  // 倒计时剩余秒数
  const count = ref(num);
  // 是否倒计时中
  const isDown = ref(false);
  // 定时器的 id 编号
  let timerId = null;
  // 开始倒计时函数
  const start = () => {
    if (isDown.value) return; //当前正在倒计时中,则返回
    isDown.value = true;      //设置 isDown 值,表示正在倒计时中
    timerId = setInterval(() => {
      count.value--;
    }, 1000);
  }
  // 使用 watch 监听 count 值,当 count 值变为 0 时,停止计时器
  watch(count, (newCount) => {
    if (newCount <= 0) {
      clearInterval(timerId); //清除计时器
      count.value = num;      //重置 count 值
      isDown.value = false;   //重置 isDown 值
    }
  })
  return {
    count,
    isDown,
    start
  }
}
        页面按钮
xxx/index.vue
            
            
              html
              
              
            
          
          <template>
  <el-button type="primary" @click="countDownFn">
    <span v-if="isDown">正在倒计时({{ count }})</span>
    <span v-else>开始倒计时</span>
  </el-button>
</template>
<script setup>
// 导入 hooks 函数
import { useCountDown } from "@/hooks"
// 调用 useCountDown 函数,得到 count计数, isDown是否开始, start 函数
const { count, isDown, start } = useCountDown(10)
// 倒计时
const countDownFn = () => {
  start()
}
</script>
<style lang="scss" scoped>
</style>