目录
一. 什么是hooks函数?
二、如何封装一个hooks函数
三、Hooks 常用 Demo
(1)验证码倒计时
(2)防抖
(3)节流
一. 什么是hooks函数?
专业解释:Vue 3中的Hooks函数是一种用于在组件中共享可复用逻辑的方式。
大白话:将单独功能的js代码抽离出来, 加工成公共函数,从而达到逻辑复用。
在尤大大开发Vue3 Composition API 主要考虑了以下两点 :
- 对Vue社区调研,了解了许多使用Vue的开发者对于更好的组件逻辑组织方式的期望。
- 对React Hooks和其他前端框架的解决方案进行了学习和借鉴。
有了composition API 意味着我们就可以自定义封装hooks,最终的目的都是进行复用,在Vue2中复用的方式大部分都是采取的mixin,但相比hooks,hooks更清楚复用的功能来源及功能。
二、如何封装一个hooks函数
例如实现一个点击按钮获取body的宽度和高度
<script setup lang="ts">
import { reactive } from "vue";
const data = reactive({
  width: 0,
  height:0
})
const getViewportSize = () => {
  data.width = document.body.clientWidth;
  data.height = document.body.clientHeight;
}
</script>
<template>
  <button @click="getViewportSize" > 获取窗口大小 </button>
    <div>
      <div>宽度 : {{data.width}}</div>
      <div>宽度 : {{data.height}}</div>
    </div>
</template>
抽离逻辑,封装成hooks函数
hooks封装规范:
1. 新建hooks文件;
2. 函数名前缀加上use;
3. 合理利用Vue提供的响应式函数及生命周期;
4. 暴露出 变量 和 方法 提供外部需要时使用;
src/hooks/index.js
import { reactive } from "vue";
export function useVwSize() {
  const data = reactive({
    width: 0,
    height:0
  })
  
  const getViewportSize = () => {
    data.width = document.body.clientWidth;
    data.height = document.body.clientHeight;
  }
  return {
    data,getViewportSize
  }
}index.vue 使用hooks
<script setup lang="ts">
import { useVwSize } from "@/hooks";
const { data, getViewportSize } = useVwSize();
</script>
<template>
  <button @click="getViewportSize">获取窗口大小</button>
  <div>
    <div>宽度 : {{ data.width }}</div>
    <div>宽度 : {{ data.height }}</div>
  </div>
</template>
三、Hooks 常用 Demo
(1)验证码倒计时
/**
 *  倒计时
 *  @param {Number} second 倒计时秒数
 *  @return {Number} count 倒计时秒数
 *  @return {Function} countDown 倒计时函数
 *  @example
 *  const { count, countDown } = useCountDown()
 *  countDown(60)
 * <div>{{ count }}</div>
 */
export function useCountDown() {
  const count = ref(0);
  const timer = ref(null);
  const countDown = (second, ck) => {
    if (count.value === 0 && timer.value === null) {
      ck();
      count.value = second;
      timer.value = setInterval(() => {
        count.value--;
        if (count.value === 0) clearInterval(timer.value);
      }, 1000);
    }
  };
  onBeforeMount(() => {
    timer.value && clearInterval(timer.value);
  });
  return {
    count,
    countDown,
  };
}
<script setup lang="ts">
import {useCountDown} from "@/hooks";
// 倒计时
const { count, countDown } = useCountDown();
const sendCode = () => {
  console.log("发送验证码");
};
</script>
 <button :disabled="count!=0" @click="countDown(5,sendCode)">倒计时 {{ count || '' }} </button>(2)防抖
/**
 * @params {Function} fn  需要防抖的函数 delay 防抖时间
 * @returns {Function} debounce 防抖函数
 * @example  
 * const { debounce } = useDebounce()
 * const fn = () => { console.log('防抖') }
 * const debounceFn = debounce(fn, 1000)
 * debounceFn()
 * 
 */
export function useDebounce() {
  const debounce = (fn, delay) => {
    let timer = null;
    return function () {
      if (timer)  clearTimeout(timer);
      timer = setTimeout(() => {
        fn.apply(this, arguments);
      }, delay);
    };
  };
  return { debounce };
}
<script setup lang="ts">
import { useDebounce } from "@/hooks";
// 防抖
const { debounce } = useDebounce()
 
const fn = () => {
   console.log('点击了哈');
}
const debounceClick =  debounce(fn,1000)
<button @click="debounceClick">防抖点击</button>
</script>(3)节流
/**
 * @params {Function} fn  需要节流的函数 delay 节流时间
 * @returns {Function} throttle 节流函数
 * @example
 * const { throttle } = useThrottle()
 * const fn = () => { console.log('节流') }
 * const throttleFn = throttle(fn, 1000)
 * throttleFn()
 *  
 * 
 *  */
export function useThrottle() {
  const throttle = (fn, delay) => {
    let timer = null;
    return function () {
      if (!timer) {
        timer = setTimeout(() => {
          fn.apply(this, arguments);
          timer = null;
        }, delay);
      }
    };
  };
  return { throttle };
}<script setup lang="ts">
import { useThrottle} from "@/hooks";
const fn = () => {
   console.log('点击了哈');
}
const { throttle } = useThrottle()
const throttleClick =  throttle(fn,1000)
</script>
 <button @click="throttleClick">节流点击</button>后面遇到不错的hooks也会持续更新哈..,也欢迎评论出你觉得不错的hooks 函数!!!




















