Vue3中Hooks函数的使用及封装思想详解
一. 什么是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>以上就是Vue3中Hooks函数的使用及封装思想详解的详细内容,更多关于Vue3 Hooks的资料请关注脚本之家其它相关文章!
相关文章
Vue.js使用this.$confirm换行显示提示信息实例
在编写Web应用时,实现多行文本显示通常需要用到HTML标签或JavaScript特定函数,本文介绍了如何使用JavaScript的$createElement函数来创建多行文本显示,$createElement可以创建任何HTML标签,使得在JavaScript中控制HTML输出更加灵活,通过简单的代码示例2024-10-10
vue代理如何配置重写方法(pathRewrite与rewrite)
这篇文章主要介绍了vue代理如何配置重写方法(pathRewrite与rewrite),具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教2024-03-03
解决vue net :ERR_CONNECTION_REFUSED报错问题
这篇文章主要介绍了解决vue net :ERR_CONNECTION_REFUSED报错问题,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧2020-08-08
vue el-table设置selection选中状态实现方式
在Vue使用Element UI的el-table组件时,toggleRowSelection方法用于切换行的选中状态,关键代码通常涉及调用该方法并传入行数据和选中状态(true或false),以实现行的选中或取消选中2025-12-12


最新评论