当前位置: 首页 > Web前端 > HTML

vue.js10个好用的自定义hook

时间:2023-04-02 14:33:41 HTML

作者:SangNguyen译者:前端小智来源:medium有梦想,有干货,微信搜索【大千世界】关注这个洗碗盘在清晨的智慧。本文已收录到GitHubhttps://github.com/qq449245884/xiaozhi,里面有完整的测试站点、资料和我的一线厂商访谈系列文章。Vue是我使用的第一个JS框架。可以说,Vue是我进入JavaScript世界的第一扇门。目前,Vue仍然是一个很棒的框架。随着组合API的出现,Vue只会增长得更多。在本文中,我将介绍10个有用的自定义钩子,让我们的代码更加美观。useWindowResize这是一个基本的钩子,因为它被用在许多项目中。从'vue'导入{ref,onMounted,onUnmounted};导出函数useWindowResize(){constwidth=ref(window.innerWidth);constheight=ref(window.innerHeight);consthandleResize=()=>{width.value=window.innerWidth;height.value=window.innerHeight;}onMounted(()=>{window.addEventListener('resize',handleResize)});onUnmounted(()=>{window.removeEventListener('resize',handleResize)})return{width,height}}使用起来比较简单,调用这个钩子就可以得到窗口的宽高。setup(){const{width,height}=useWindowResize();}useStorage您想通过将数据的值存储在会话存储或本地存储并将该值绑定到视图来持久化数据吗?使用一个简单的钩子--useStorage,这变得非常容易。我们只需要创建一个钩子来返回我们从存储中获取的数据,以及一个函数来在我们想要更改数据时将数据存储在存储中。下面是我的钩子。import{ref}from'vue';constgetItem=(key,storage)=>{letvalue=storage.getItem(key);如果(!值){返回空值;}try{returnJSON.parse(value)}catch(error){返回值;}}exportconstuseStorage=(key,type='session')=>{letstorage=null;switch(type){case'session':storage=sessionStorage;休息;case'local':storage=localStorage;休息;默认值:返回空值;}constvalue=ref(getItem(key,storage));constsetItem=(storage)=>{return(newValue)=>{value.value=newValue;存储.setItem(key,JSON.stringify(newValue));}}return[value,setItem(storage)]}在我的代码中,我使用JSON.parse和JSON.stringify来格式化数据。如果你不想格式化它,你可以删除它。下面是一个如何使用这个钩子的例子。const[token,setToken]=useStorage('token');setToken('newtoken');useNetworkStatus这是一个有用的钩子,支持检查网络连接的状态。要实现这个钩子,我们需要为“在线”和“离线”事件添加事件监听器。在事件中,我们只是调用一个以网络状态为参数的回调函数。下面是我的代码。import{onMounted,onUnmounted}from'vue';exportconstuseNetworkStatus=(callback=()=>{})=>{constupdateOnlineStatus=()=>{conststatus=navigator.onLine?'在线':'离线';回调(状态);}onMounted(()=>{window.addEventListener('online',updateOnlineStatus);window.addEventListener('offline',updateOnlineStatus);});onUnmounted(()=>{window.removeEventListener('online',updateOnlineStatus);window.removeEventListener('offline',updateOnlineStatus);})}调用方法:useNetworkStatus((status)=>{console.log(`你的网络statusis${status}`);}useCopyToClipboardClipboard是一个比较常用的函数,我们也可以把它封装成一个hook,代码如下:functioncopyToClipboard(text){letinput=document.createElement('input');input.setAttribute('value',text);document.body.appendChild(input);input.select();letresult=document.execCommand('copy');document.body.removeChild(input);返回结果;}导出常量useCopyToClipboard=()=>{return(text)=>{if(typeoftext==="string"||typeoftext=="number"){returncopyToClipboard(text);}返回假;}}使用如下:constcopyToClipboard=useCopyToClipboard();copyToClipboard('justcopy');useTheme只是一个更改网站主题的小钩子,它可以帮助我们轻松地切换网站的主题,只需用主题名称调用这个钩子即可。下面是我用来定义主题变量的CSS代码示例。html[theme="dark"]{--color:#FFF;--background:#333;}html[theme="default"],html{--color:#333;--background:#FFF;}要更改主题,只需制作一个自定义挂钩,该挂钩返回一个函数以按主题名称更改主题。代码如下:exportconstuseTheme=(key='')=>{return(theme)=>{document.documentElement.setAttribute(key,theme);}}使用如下:constchangeTheme=useTheme();changeTheme('dark');usePageVisibility有时我们需要在客户不关注我们的网站时做一些事情。为此,我们需要一些东西让我们知道用户是否在关注。这是一个自定义挂钩。我把它叫做PageVisibility,代码如下:import{onMounted,onUnmounted}from'vue';exportconstusePageVisibility=(callback=()=>{})=>{lethidden,visibilityChange;如果(typeofdocument.hidden!=="undefined"){hidden="hidden";visibilityChange="visibilitychange";}elseif(typeofdocument.msHidden!=="undefined"){hidden="msHidden";visibilityChange="msvisibilitychange";}elseif(typeofdocument.webkitHidden!=="undefined"){hidden="webkitHidden";visibilityChange="webkitvisibilitychange";}consthandleVisibilityChange=()=>{回调(文档[隐藏]);}onMounted(()=>{document.addEventListener(visibilityChange,handleVisibilityChange,false);});onUnmounted(()=>{document.removeEventListener(visibilityChange,handleVisibilityChange);});}使用方法如下:usePageVisibility((hidden)=>{console.log(`Useris${hidden?'not':''}focusyoursite`);});useViewport有时候我们会用宽度来检测当前用户设备,这样我们就可以根据设备内容我们也可以把这个场景封装成一个钩子,代码如下:import{ref,onMounted,onUnmounted}from'vue';exportconstMOBILE='MOBILE'exportconstTABLET='TABLET'exportconstDESKTOP='DESKTOP'exportconstuseViewport=(config={})=>{const{mobile=null,tablet=null}=config;让mobileWidth=移动?手机:768;让tabletWidth=平板电脑?片剂:922;让设备=ref(getDevice(window.innerWidth));functiongetDevice(width){if(width{device.value=getDevice(window.innerWidth);}onMounted(()=>{window.addEventListener('resize',handleResize);});onUnmounted(()=>{window.removeEventListener('resize',handleResize);});return{device}}用法如下:const{device}=useViewport({mobile:700,table:900});使用OnClickOutside当模型框弹出时,我们希望点击其他区域来关闭它,这个可以使用clic来完成kOutSide,我们也可以把这个场景封装成hook,代码如下:import{onMounted,onUnmounted}from'vue';exportconstuseOnClickOutside=(ref=null,callback=()=>{})=>{functionhandleClickOutside(event){if(ref.value&&!ref.value.contains(event.target)){callback()}}onMounted(()=>{document.addEventListener('mousedown',handleClickOutside);})onUnmounted(()=>{document.removeEventListener('mousedown',handleClickOutside);});}用法如下:useScrollToBottom除了分页列表,加载更多(或延迟加载)是一种加载数据的友好方式,尤其是对于移动设备,几乎所有在移动设备上运行的应用程序都在其用户界面中应用更多负载。为此,我们需要检测到用户已滚动到列表底部并为该事件触发回调。useScrollToBottom是一个有用的挂钩,可让您执行此操作。代码如下:import{onMounted,onUnmounted}from'vue';exportconstuseScrollToBottom=(callback=()=>{})=>{consthandleScrolling=()=>{if((window.innerHeight+window.scrollY)>=document.body.scrollHeight){回调();}}onMounted(()=>{window.addEventListener('scroll',handleScrolling);});onUnmounted(()=>{window.removeEventListener('scroll',handleScrolling);});}用法如下:useScrollToBottom(()=>{console.log('Scrolledtobottom')})useTimer的代码useTimer比其他钩子要长一些。useTimer支持使用启动、暂停/恢复、停止等选项运行计时器。为此,我们需要使用setInterval方法。在这里,我们需要检查定时器的暂停状态。如果计时器没有暂停,我们只需要调用一个回调函数,该函数由用户作为参数传递。为了支持用户了解定时器当前的暂停状态,除了actionuseTimer之外,还给他们一个变量isPaused,其值为定时器的暂停状态。代码如下:import{ref,onUnmounted}from'vue';exportconstuseTimer=(callback=()=>{},step=1000)=>{lettimerVariableId=null;让时间=0;constisPaused=ref(false);conststop=()=>{if(timerVariableId){clearInterval(timerVariableId);timerVariableId=null;恢复();}}conststart=()=>{停止();如果(!timerVariableId){次=0;timerVariableId=setInterval(()=>{if(!isPaused.value){times++;callback(times,step*times);}},step)}}constpause=()=>{isPaused.value=true;}constresume=()=>{isPaused.value=false;}onUnmounted(()=>{if(timerVariableId){clearInterval(timerVariableId);}})return{start,stop,pause,resume,isPaused}}使用方法如下:functionhandleTimer(round){roundNumber.value=round;}const{开始,停止,pause,resume,isPaused}=useTimer(handleTimer);本文分享了10个有用的Vue自定义钩子,希望对你有所帮助。看。这是一个很棒的框架,我希望你能用它来构建更酷的东西。代码部署后可能存在的bug,无法实时获知。事后为了解决这些bug,花费了大量的时间在日志调试上。顺便推荐一个好用的bug监控工具Fundebug。原文:https://javascript.plainengli...交流有梦想,有干货,微信搜索【伟大的走向世界】关注这位凌晨还在洗碗的洗碗智慧。本文已收录到GitHubhttps://github.com/qq449245884/xiaozhi,里面有完整的测试站点、资料和我的一线厂商访谈系列文章。