23個(gè)不可錯(cuò)過(guò)的Vue3實(shí)用Hook
前言
為了進(jìn)一步提升開(kāi)發(fā)效率和代碼質(zhì)量,@vueuse/core 作為一款基于 Vue 3 Composition API 的實(shí)用工具庫(kù),提供了豐富的功能性鉤子,使得處理常見(jiàn)的開(kāi)發(fā)任務(wù)變得更加簡(jiǎn)潔和高效。
本文將詳細(xì)介紹如何在 Vue 3 項(xiàng)目中使用 @vueuse/core 及其一些極具價(jià)值的功能,以幫助開(kāi)發(fā)者更好地應(yīng)對(duì)復(fù)雜的開(kāi)發(fā)需求。
什么是 @vueuse/core
@vueuse/core 是一個(gè)面向 Vue 3 的工具庫(kù),提供了一組基于 Composition API 的實(shí)用函數(shù)。它可以幫助我們更輕松地處理常見(jiàn)的開(kāi)發(fā)任務(wù),比如狀態(tài)管理、瀏覽器 API 集成、時(shí)間處理等等。
為什么要用 @vueuse/core
提高開(kāi)發(fā)效率:提供豐富的實(shí)用函數(shù),減少代碼量。
提升代碼可讀性:函數(shù)封裝良好,使代碼更易讀。
活躍的社區(qū)支持:持續(xù)更新和完善,社區(qū)活躍。
@vueuse/core 常用功能
1. useMouse
useMouse 可以讓你輕松獲取鼠標(biāo)指針的位置。想象一下,你需要在頁(yè)面上顯示鼠標(biāo)的位置,大致是這樣的代碼:
import { useMouse } from '@vueuse/core'; export default { setup() { const { x, y } = useMouse(); return { x, y }; }, }; //在模板中使用: <template> <div> 鼠標(biāo)位置: ({{ x }}, {{ y }}) </div> </template>
2. useFetch
useFetch 是一個(gè)很方便的工具,用來(lái)處理 HTTP 請(qǐng)求。假設(shè)你需要從 API 獲取數(shù)據(jù):
import { useFetch } from '@vueuse/core'; ???????export default { setup() { const { data, error, isFetching } = useFetch('https://api.example.com/data').json(); return { data, error, isFetching }; }, }; //在模板中展示數(shù)據(jù): <template> <div> <div v-if="isFetching">加載中...</div> <div v-else-if="error">出錯(cuò)了: {{ error.message }}</div> <div v-else>{{ data }}</div> </div> </template>
3. useLocalStorage
useLocalStorage 讓你輕松讀寫(xiě)瀏覽器的 localStorage。比如,你想保存用戶(hù)的偏好設(shè)置:
import { useLocalStorage } from '@vueuse/core'; ???????export default { setup() { const theme = useLocalStorage('theme', 'light'); return { theme }; }, }; //在模板中綁定到用戶(hù)界面: <template> <div> <select v-model="theme"> <option value="light">淺色</option> <option value="dark">深色</option> </select> </div> </template>
4. useDark
useDark 讓你輕松實(shí)現(xiàn)深色模式的切換:
import { useDark, useToggle } from '@vueuse/core'; export default { setup() { const isDark = useDark(); const toggleDark = useToggle(isDark); return { isDark, toggleDark }; }, }; ???????//在模板中添加切換按鈕: <template> <div> <button @click="toggleDark"> 切換到 {{ isDark ? '淺色' : '深色' }} 模式 </button> </div> </template>
5. useDebounce
useDebounce 是一個(gè)非常實(shí)用的函數(shù),用于處理高頻率調(diào)用的場(chǎng)景,比如搜索框輸入時(shí)的自動(dòng)補(bǔ)全。它可以有效防止函數(shù)在短時(shí)間內(nèi)被多次調(diào)用。
import { ref } from 'vue'; import { useDebounce } from '@vueuse/core'; export default { setup() { const searchQuery = ref(''); const debouncedQuery = useDebounce(searchQuery, 300); // 300ms 的防抖 watch(debouncedQuery, (newValue) => { // 這里可以進(jìn)行 API 請(qǐng)求或其他操作 console.log('API 調(diào)用查詢(xún): ', newValue); }); return { searchQuery }; }, }; //在模板中使用: <template> <div> <input v-model="searchQuery" placeholder="輸入查詢(xún)內(nèi)容..." /> </div> </template>
6. useDeviceOrientation
useDeviceOrientation 讓你可以輕松獲取設(shè)備的方向信息。這個(gè)功能在移動(dòng)端開(kāi)發(fā)中尤為重要,比如做游戲或界面旋轉(zhuǎn)適配。
import { useDeviceOrientation } from '@vueuse/core'; export default { setup() { const { alpha, beta, gamma } = useDeviceOrientation(); return { alpha, beta, gamma }; }, }; //在模板中顯示設(shè)備方向: <template> <div> <div>Alpha: {{ alpha }}</div> <div>Beta: {{ beta }}</div> <div>Gamma: {{ gamma }}</div> </div> </template>
7. useNetwork
useNetwork 讓你可以檢測(cè)用戶(hù)的網(wǎng)絡(luò)狀態(tài),比如在線(xiàn)或離線(xiàn),甚至可以監(jiān)控網(wǎng)絡(luò)的類(lèi)型(如 wifi、4g 等)。
import { useNetwork } from '@vueuse/core'; export default { setup() { const { isOnline, saveData, connectionType } = useNetwork(); return { isOnline, saveData, connectionType }; }, }; //在模板中顯示網(wǎng)絡(luò)狀態(tài): <template> <div> <div>網(wǎng)絡(luò)狀態(tài): {{ isOnline ? '在線(xiàn)' : '離線(xiàn)' }}</div> <div>連接類(lèi)型: {{ connectionType }}</div> <div>是否節(jié)省數(shù)據(jù): {{ saveData }}</div> </div> </template>
8. useBattery
useBattery 可以讓你獲取設(shè)備的電池狀態(tài)信息,這在移動(dòng)應(yīng)用中非常有用。
import { useBattery } from '@vueuse/core'; export default { setup() { const { isCharging, chargingTime, dischargingTime, level } = useBattery(); return { isCharging, chargingTime, dischargingTime, level }; }, }; //在模板中顯示電池狀態(tài): <template> <div> <div>正在充電: {{ isCharging ? '是' : '否' }}</div> <div>電池電量: {{ level * 100 }}%</div> <div>充電時(shí)間: {{ chargingTime }} 秒</div> <div>放電時(shí)間: {{ dischargingTime }} 秒</div> </div> </template>
9. useWindowSize
useWindowSize 可以讓你實(shí)時(shí)獲取窗口的寬度和高度,非常適合響應(yīng)式設(shè)計(jì)。
import { useWindowSize } from '@vueuse/core'; export default { setup() { const { width, height } = useWindowSize(); return { width, height }; }, }; //在模板中顯示窗口尺寸: <template> <div> <div>窗口寬度: {{ width }} px</div> <div>窗口高度: {{ height }} px</div> </div> </template>
10. usePreferredDark
usePreferredDark 可以幫助你自動(dòng)檢測(cè)用戶(hù)的系統(tǒng)深色模式偏好,并在你的應(yīng)用中做出相應(yīng)的調(diào)整。這對(duì)于創(chuàng)建符合用戶(hù)習(xí)慣的界面非常有幫助。
import { usePreferredDark } from '@vueuse/core'; export default { setup() { const isDarkPreferred = usePreferredDark(); return { isDarkPreferred }; }, }; //在模板中使用: <template> <div> <div>系統(tǒng)深色模式偏好: {{ isDarkPreferred ? '深色' : '淺色' }}</div> </div> </template>
11. useClipboard
useClipboard 提供了便捷的剪貼板操作功能,可以輕松實(shí)現(xiàn)文本的復(fù)制和粘貼。例如,你需要實(shí)現(xiàn)一個(gè)“復(fù)制到剪貼板”的功能:
import { useClipboard } from '@vueuse/core'; export default { setup() { const { copy, copied } = useClipboard(); const copyText = async () => { await copy('要復(fù)制的文本'); }; return { copyText, copied }; }, }; //在模板中添加按鈕: <template> <div> <button @click="copyText">復(fù)制文本</button> <div v-if="copied">已復(fù)制!</div> </div> </template>
12. useGeolocation
useGeolocation 讓你可以輕松獲取用戶(hù)的位置,這是很多地理位置相關(guān)應(yīng)用的核心功能。
import { useGeolocation } from '@vueuse/core'; export default { setup() { const { coords, locatedAt, error } = useGeolocation(); return { coords, locatedAt, error }; }, }; //在模板中顯示地理位置: <template> <div> <div v-if="error">定位失敗: {{ error.message }}</div> <div v-else> <div>緯度: {{ coords.latitude }}</div> <div>經(jīng)度: {{ coords.longitude }}</div> <div>定位時(shí)間: {{ locatedAt }}</div> </div> </div> </template>
13. useTitle
useTitle 允許你動(dòng)態(tài)地設(shè)置和獲取頁(yè)面的標(biāo)題。這在單頁(yè)面應(yīng)用中尤其有用,可以讓每個(gè)路由有自己獨(dú)特的標(biāo)題。
import { useTitle } from '@vueuse/core'; export default { setup() { const title = useTitle(); title.value = '我的 Vue 應(yīng)用'; return { title }; }, }; //在模板中: <template> <div> <input v-model="title" placeholder="修改頁(yè)面標(biāo)題" /> </div> </template>
14. useIdle
useIdle 可以檢測(cè)用戶(hù)是否處于閑置狀態(tài)。這個(gè)功能可以用來(lái)實(shí)現(xiàn)用戶(hù)不活動(dòng)時(shí)自動(dòng)登出等功能。
import { useIdle } from '@vueuse/core'; export default { setup() { const isIdle = useIdle(5000); // 設(shè)置閑置時(shí)間為 5 秒 return { isIdle }; }, }; //在模板中顯示用戶(hù)狀態(tài): <template> <div> <div>用戶(hù)狀態(tài): {{ isIdle ? '閑置' : '活躍' }}</div> </div> </template>
15. useEventListener
useEventListener 可以讓你更方便地添加和管理事件監(jiān)聽(tīng)器,特別適合需要在組件卸載時(shí)自動(dòng)移除事件監(jiān)聽(tīng)的場(chǎng)景。
import { ref } from 'vue'; import { useEventListener } from '@vueuse/core'; export default { setup() { const count = ref(0); useEventListener(window, 'click', () => { count.value += 1; }); return { count }; }, }; //在模板中顯示點(diǎn)擊次數(shù): <template> <div> <div>點(diǎn)擊次數(shù): {{ count }}</div> </div> </template>
16. useMediaQuery
useMediaQuery 可以讓你根據(jù)媒體查詢(xún)條件檢測(cè)設(shè)備的狀態(tài),這對(duì)于響應(yīng)式設(shè)計(jì)和不同設(shè)備適配非常有用。
import { useMediaQuery } from '@vueuse/core'; export default { setup() { const isLargeScreen = useMediaQuery('(min-width: 1024px)'); return { isLargeScreen }; }, }; //在模板中顯示不同設(shè)備狀態(tài): <template> <div> <div>設(shè)備狀態(tài): {{ isLargeScreen ? '大屏幕' : '小屏幕' }}</div> </div> </template>
17. useIntersectionObserver
useIntersectionObserver 讓你可以檢測(cè)某個(gè)元素是否可見(jiàn),并且可以執(zhí)行相應(yīng)的操作,比如實(shí)現(xiàn)圖片懶加載等。
import { ref } from 'vue'; import { useIntersectionObserver } from '@vueuse/core'; export default { setup() { const target = ref(null); const { isIntersecting } = useIntersectionObserver(target, { threshold: 0.1, }); return { target, isIntersecting }; }, }; //在模板中實(shí)現(xiàn)懶加載圖片: <template> <div ref="target"> <img v-if="isIntersecting" src="path/to/your/image.jpg" alt="Lazy Loaded Image" /> <div v-else>加載中...</div> </div> </template>
18. useParallax
useParallax 讓你輕松實(shí)現(xiàn)視差滾動(dòng)效果,這在現(xiàn)代網(wǎng)頁(yè)設(shè)計(jì)中非常流行。
import { ref } from 'vue'; import { useParallax } from '@vueuse/core'; export default { setup() { const target = ref(null); const { x, y } = useParallax(target, { factor: 0.5, }); return { target, x, y }; }, }; //在模板中實(shí)現(xiàn)視差效果: <template> <div ref="target" :style="{ transform: `translate3d(${x}px, ${y}px, 0)` }"> 視差效果元素 </div> </template>
19. useResizeObserver
useResizeObserver 用于監(jiān)聽(tīng)元素的尺寸變化,這對(duì)于響應(yīng)式布局和動(dòng)態(tài)元素非常有用。
import { ref } from 'vue'; import { useResizeObserver } from '@vueuse/core'; export default { setup() { const target = ref(null); const size = ref({ width: 0, height: 0 }); useResizeObserver(target, (entries) => { for (let entry of entries) { size.value.width = entry.contentRect.width; size.value.height = entry.contentRect.height; } }); return { target, size }; }, }; //在模板中顯示元素尺寸: <template> <div ref="target"> <div>寬度: {{ size.width }} px</div> <div>高度: {{ size.height }} px</div> </div> </template>
20. useSessionStorage
useSessionStorage 讓你輕松操作 sessionStorage,和 useLocalStorage 類(lèi)似,但數(shù)據(jù)僅在會(huì)話(huà)期間存在。
import { useSessionStorage } from '@vueuse/core'; export default { setup() { const user = useSessionStorage('user', { name: 'John Doe' }); return { user }; }, }; //在模板中使用: <template> <div> <input v-model="user.name" placeholder="用戶(hù)名" /> <div>當(dāng)前用戶(hù): {{ user.name }}</div> </div> </template>
21. useElementBounding
useElementBounding 可以獲取一個(gè)元素的邊界信息(比如位置和尺寸),這對(duì)于復(fù)雜布局和動(dòng)畫(huà)效果很有幫助。
import { ref } from 'vue'; import { useElementBounding } from '@vueuse/core'; export default { setup() { const target = ref(null); const { top, left, width, height } = useElementBounding(target); return { target, top, left, width, height }; }, }; //在模板中顯示元素邊界信息: <template> <div ref="target"> <div>頂部: {{ top }} px</div> <div>左部: {{ left }} px</div> <div>寬度: {{ width }} px</div> <div>高度: {{ height }} px</div> </div> </template>
22. useOnline
useOnline 允許你檢測(cè)用戶(hù)是否在線(xiàn),這在處理離線(xiàn)狀態(tài)和數(shù)據(jù)同步時(shí)非常有用。
import { useOnline } from '@vueuse/core'; export default { setup() { const isOnline = useOnline(); return { isOnline }; }, }; //在模板中顯示在線(xiàn)狀態(tài): <template> <div> <div>網(wǎng)絡(luò)狀態(tài): {{ isOnline ? '在線(xiàn)' : '離線(xiàn)' }}</div> </div> </template>
23. usePreferredLanguages
usePreferredLanguages 可以獲取用戶(hù)的首選語(yǔ)言列表,這在多語(yǔ)言支持的應(yīng)用中非常有用。
import { usePreferredLanguages } from '@vueuse/core'; export default { setup() { const preferredLanguages = usePreferredLanguages(); return { preferredLanguages }; }, }; //在模板中顯示首選語(yǔ)言: <template> <div> <div>首選語(yǔ)言: {{ preferredLanguages.join(', ') }}</div> </div> </template>
總結(jié)
通過(guò)本文對(duì) @vueuse/core 的詳細(xì)介紹,我們可以看到這個(gè)工具庫(kù)為 Vue 3 項(xiàng)目帶來(lái)了眾多便捷和強(qiáng)大的功能,大大簡(jiǎn)化了開(kāi)發(fā)過(guò)程。無(wú)論是狀態(tài)管理、設(shè)備信息獲取還是瀏覽器 API 集成,@vueuse/core 都提供了完善的解決方案,幫助開(kāi)發(fā)者實(shí)現(xiàn)高效、優(yōu)雅的代碼。在實(shí)際項(xiàng)目中,充分利用這些工具不僅能提升開(kāi)發(fā)效率,還能優(yōu)化用戶(hù)體驗(yàn)。
到此這篇關(guān)于23個(gè)不可錯(cuò)過(guò)的Vue3實(shí)用Hook的文章就介紹到這了,更多相關(guān)Vue3實(shí)用Hook內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
vue中使用cookies和crypto-js實(shí)現(xiàn)記住密碼和加密的方法
這篇文章給大家介紹一下關(guān)于vue中使用cookies和crypto-js如何實(shí)現(xiàn)密碼的加密與記住密碼,有一定的參考價(jià)值,有需要的朋友可以參考一下,希望對(duì)你們有所幫助。2018-10-10vue中使用iconfont圖標(biāo)的過(guò)程
這篇文章主要介紹了vue中使用iconfont圖標(biāo)的過(guò)程,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-08-08vue+elementUi 實(shí)現(xiàn)密碼顯示/隱藏+小圖標(biāo)變化功能
這篇文章主要介紹了vue+elementUi 實(shí)現(xiàn)密碼顯示/隱藏+小圖標(biāo)變化功能,需本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-01-01詳解vue-cli4 配置不同開(kāi)發(fā)環(huán)境打包命令
這篇文章主要介紹了vue-cli4 配置不同開(kāi)發(fā)環(huán)境打包命令,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2023-07-07一步步教你搭建VUE+VScode+elementUI開(kāi)發(fā)環(huán)境
這篇文章主要給大家介紹了關(guān)于搭建VUE+VScode+elementUI開(kāi)發(fā)環(huán)境的相關(guān)資料,近期被配置環(huán)境的事情弄得整個(gè)人都要炸了,現(xiàn)在整理如下,希望有相同需求的朋友可以不用走彎路,需要的朋友可以參考下2023-07-07Vue開(kāi)發(fā)環(huán)境跨域訪(fǎng)問(wèn)問(wèn)題
這篇文章主要介紹了Vue開(kāi)發(fā)環(huán)境跨域訪(fǎng)問(wèn)問(wèn)題,本文給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-01-01