Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to customize the Vue hook function

2025-01-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly explains "how to customize the Vue hook function", the content of the article is simple and clear, easy to learn and understand, the following please follow the editor's ideas slowly in depth, together to study and learn "how to customize the Vue hook function" bar!

UseWindowResize

This is a basic hook because it is used in many projects.

Import {ref, onMounted, onUnmounted} from 'vue';export function useWindowResize () {const width = ref (window.innerWidth); const height = ref (window.innerHeight); const handleResize = > {width.value = window.innerWidth; height.value = window.innerHeight;} onMounted (() = > {window.addEventListener (' resize', handleResize)}); onUnmounted () = > {window.removeEventListener ('resize', handleResize)}) return {width, height}}

It's even easier to use, just call this hook to get the width and height of the window.

Setup () {const {width, height} = useWindowResize ();} useStorage

Do you want to persist the data by storing the value of the data in session storage or local storage and bind the value to the view? With a simple hook, useStorage, this will become very easy. We just need to create a hook to return the data from the storage space and a function to store the data in the storage space when we want to change it. Here's my hook.

Import {ref} from 'vue';const getItem = (key, storage) = > {let value = storage.getItem (key); if (! value) {return null;} try {return JSON.parse (value)} catch (error) {return value;}} export const useStorage = (key, type =' session') = > {let storage = null; switch (type) {case 'session': storage = sessionStorage; break Case 'local': storage = localStorage; break; default: return null;} const value = ref (getItem (key, storage)); const setItem = (storage) = > {return (newValue) = > {value.value = newValue; storage.setItem (key, JSON.stringify (newValue));} return [value, setItem (storage)]}

In my code, I use JSON.parse * * and JSON.stringify** to format data. If you don't want to format it, you can delete it. Here is an example of how to use this hook.

Const [token, setToken] = useStorage ('token'); setToken (' new token'); useNetworkStatus

This is a useful hook that supports checking the status of network connections. To implement this hook, we need to add event listeners for events "online" and "offline". In the event, we just call a callback function with an argument to the network state. Here is my code.

Import {onMounted, onUnmounted} from 'vue';export const useNetworkStatus = (callback = () = > {}) = > {const updateOnlineStatus = () = > {const status = navigator.onLine? 'online':' offline'; callback (status);} onMounted (() = > {window.addEventListener ('online', updateOnlineStatus); window.addEventListener (' offline', updateOnlineStatus);}); onUnmounted () = > {window.removeEventListener ('online', updateOnlineStatus); window.removeEventListener (' offline', updateOnlineStatus);})}

Call method:

UseNetworkStatus ((status) = > {console.log (`Your network status is ${status} `);} useCopyToClipboard

Clipboard is a common feature. We can also encapsulate it into hook. The code is as follows:

Function copyToClipboard (text) {let input = document.createElement ('input'); input.setAttribute (' value', text); document.body.appendChild (input); input.select (); let result = document.execCommand ('copy'); document.body.removeChild (input); return result;} export const useCopyToClipboard = () = > {return (text) = > {if (typeof text = = "string" | | typeof text = = "number") {return copyToClipboard (text);} return false;}}

The use is as follows:

Const copyToClipboard = useCopyToClipboard (); copyToClipboard ('just copy'); useTheme

It's just a short hook to change the theme of the site. It can help us easily change the theme of the site by calling the hook with the theme name. The following is an example of CSS code that I use to define theme variables.

Html [theme= "dark"] {--color: # FFF;-- background: # 333;} html [theme= "default"], html {--color: # 333;-- background: # FFF;}

To change the theme, you only need to make a custom hook, which returns a function to change the theme by the theme name. The code is as follows:

Export const useTheme = (key =') = > {return (theme) = > {document.documentElement.setAttribute (key, theme);}}

The use is as follows:

Const changeTheme = useTheme (); changeTheme ('dark'); usePageVisibility

Sometimes, when customers are not focused on our site, we need to do something. To do this, we need something to let us know if users are paying attention. This is a custom hook. I call it PageVisibility, and the code is as follows:

Import {onMounted, onUnmounted} from 'vue';export const usePageVisibility = (callback = () = > {}) = > {let hidden, visibilityChange; if (typeof document.hidden! = = "undefined") {hidden = "hidden"; visibilityChange = "visibilitychange";} else if (typeof document.msHidden! = = "undefined") {hidden = "msHidden"; visibilityChange = "msvisibilitychange";} else if (typeof document.webkitHidden! = "undefined") {hidden = "webkitHidden"; visibilityChange = "webkitvisibilitychange" } const handleVisibilityChange = () = > {callback (document [hidden]);} onMounted () = > {document.addEventListener (visibilityChange, handleVisibilityChange, false);}); onUnmounted (() = > {document.removeEventListener (visibilityChange, handleVisibilityChange);});}

The usage is as follows:

UsePageVisibility ((hidden) = > {console.log (`User is$ {hidden?' Not':''} focus your site`);}); useViewport

Sometimes we use width to detect the current user device, so that we can process the corresponding content according to the device. For this scenario, we can also encapsulate it into a hook with the following code:

Import {ref, onMounted, onUnmounted} from 'vue';export const MOBILE =' MOBILE'export const TABLET = 'TABLET'export const DESKTOP =' DESKTOP'export const useViewport = (config = {}) = > {const {mobile = null, tablet = null} = config; let mobileWidth = mobile? mobile: 768; let tabletWidth = tablet? tablet: 922; let device = ref (getDevice (window.innerWidth)); function getDevice (width) {if (width)

< mobileWidth) { return MOBILE; } else if (width < tabletWidth) { return TABLET; } return DESKTOP; } const handleResize = () =>

{device.value = getDevice (window.innerWidth);} onMounted (() = > {window.addEventListener ('resize', handleResize);}); onUnmounted (() = > {window.removeEventListener (' resize', handleResize);}); return {device}}

The use is as follows:

Const {device} = useViewport ({mobile: 700,900}); useOnClickOutside

When the model box pops up, we want to click on another area to close it. This can be done using clickOutSide, and this scenario can also be encapsulated as a hook. The code is as follows:

Import {onMounted, onUnmounted} from 'vue';export const useOnClickOutside = (ref = null, callback = () = > {}) = > {function handleClickOutside (event) {if (ref.value & &! ref.value.contains (event.target)) {callback ()}} onMounted (() = > {document.addEventListener (' mousedown', handleClickOutside);}) onUnmounted (() = > {document.removeEventListener ('mousedown', handleClickOutside);});}

The usage is as follows:

Viewimport {ref} from 'vue';export default {setup () {const container = ref (null); useOnClickOutside (container, () = > {console.log (' Clicked outside');})} useScrollToBottom

In addition to paging lists, loading more (or lazy loading) is a friendly way to load data. Especially for mobile devices, almost all applications running on mobile devices apply load more in their user interface. To do this, we need to detect that the user scrolls to the bottom of the list and triggers a callback for the event.

UseScrollToBottom is a useful hook that supports you to do so. The code is as follows:

Import {onMounted, onUnmounted} from 'vue';export const useScrollToBottom = (callback = () = > {}) = > {const handleScrolling = () = > {if ((window.innerHeight + window.scrollY) > = document.body.scrollHeight) {callback ();}} onMounted (() = > {window.addEventListener (' scroll', handleScrolling);}); onUnmounted () = > {window.removeEventListener ('scroll', handleScrolling);});}

The usage is as follows:

UseScrollToBottom (() = > {console.log ('Scrolled to bottom')}) useTimer

The code for useTimer is a little longer than other hooks. UseTimer supports running a timer with options such as start, pause / resume, and stop. To do this, we need to use the setInterval method. Here, we need to check the pause state of the timer. If the timer is not paused, we only need to call a callback function, which is passed by the user as an argument. In order to support users to understand the current paused state of the timer, in addition to action useTimer, give them a variable isPaused, whose value is the paused state of the timer. The code is as follows:

Import {ref, onUnmounted} from 'vue';export const useTimer = (callback = () = > {}, step = 1000) = > {let timerVariableId = null; let times = 0; const isPaused = ref (false); const stop = () = > {if (timerVariableId) {clearInterval (timerVariableId); timerVariableId = null; resume ();}} const start = () = > {stop (); if (! timerVariableId) {times = 0 TimerVariableId = setInterval (() = > {if (! isPaused.value) {times++; callback (times, step * times);}}, step)}} const pause = () = > {isPaused.value = true;} const resume = () = > {isPaused.value = false;} onUnmounted (() = > {if (timerVariableId) {clearInterval (timerVariableId) }) return {start, stop, pause, resume, isPaused}}

The usage is as follows:

Function handleTimer (round) {roundNumber.value = round;} const {start, stop, pause, resume, isPaused} = useTimer (handleTimer); thank you for reading, the above is the content of "how to customize Vue hook function", after the study of this article, I believe you have a deeper understanding of how to customize Vue hook function, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report