23個(gè)不可錯(cuò)過的Vue3實(shí)用Hook
前言
為了進(jìn)一步提升開發(fā)效率和代碼質(zhì)量,@vueuse/core 作為一款基于 Vue 3 Composition API 的實(shí)用工具庫,提供了豐富的功能性鉤子,使得處理常見的開發(fā)任務(wù)變得更加簡潔和高效。
本文將詳細(xì)介紹如何在 Vue 3 項(xiàng)目中使用 @vueuse/core 及其一些極具價(jià)值的功能,以幫助開發(fā)者更好地應(yīng)對復(fù)雜的開發(fā)需求。
什么是 @vueuse/core
@vueuse/core 是一個(gè)面向 Vue 3 的工具庫,提供了一組基于 Composition API 的實(shí)用函數(shù)。它可以幫助我們更輕松地處理常見的開發(fā)任務(wù),比如狀態(tài)管理、瀏覽器 API 集成、時(shí)間處理等等。
為什么要用 @vueuse/core
提高開發(fā)效率:提供豐富的實(shí)用函數(shù),減少代碼量。
提升代碼可讀性:函數(shù)封裝良好,使代碼更易讀。
活躍的社區(qū)支持:持續(xù)更新和完善,社區(qū)活躍。
@vueuse/core 常用功能
1. useMouse
useMouse 可以讓你輕松獲取鼠標(biāo)指針的位置。想象一下,你需要在頁面上顯示鼠標(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è)很方便的工具,用來處理 HTTP 請求。假設(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 讓你輕松讀寫瀏覽器的 localStorage。比如,你想保存用戶的偏好設(shè)置:
import { useLocalStorage } from '@vueuse/core';
???????export default {
setup() {
const theme = useLocalStorage('theme', 'light');
return { theme };
},
};
//在模板中綁定到用戶界面:
<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)用的場景,比如搜索框輸入時(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 請求或其他操作
console.log('API 調(diào)用查詢: ', newValue);
});
return { searchQuery };
},
};
//在模板中使用:
<template>
<div>
<input v-model="searchQuery" placeholder="輸入查詢內(nèi)容..." />
</div>
</template>
6. useDeviceOrientation
useDeviceOrientation 讓你可以輕松獲取設(shè)備的方向信息。這個(gè)功能在移動(dòng)端開發(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 讓你可以檢測用戶的網(wǎng)絡(luò)狀態(tài),比如在線或離線,甚至可以監(jiān)控網(wǎng)絡(luò)的類型(如 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 ? '在線' : '離線' }}</div>
<div>連接類型: {{ 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)檢測用戶的系統(tǒng)深色模式偏好,并在你的應(yīng)用中做出相應(yīng)的調(diào)整。這對于創(chuàng)建符合用戶習(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 讓你可以輕松獲取用戶的位置,這是很多地理位置相關(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è)置和獲取頁面的標(biāo)題。這在單頁面應(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="修改頁面標(biāo)題" />
</div>
</template>
14. useIdle
useIdle 可以檢測用戶是否處于閑置狀態(tài)。這個(gè)功能可以用來實(shí)現(xiàn)用戶不活動(dòng)時(shí)自動(dòng)登出等功能。
import { useIdle } from '@vueuse/core';
export default {
setup() {
const isIdle = useIdle(5000); // 設(shè)置閑置時(shí)間為 5 秒
return { isIdle };
},
};
//在模板中顯示用戶狀態(tài):
<template>
<div>
<div>用戶狀態(tài): {{ isIdle ? '閑置' : '活躍' }}</div>
</div>
</template>
15. useEventListener
useEventListener 可以讓你更方便地添加和管理事件監(jiān)聽器,特別適合需要在組件卸載時(shí)自動(dòng)移除事件監(jiān)聽的場景。
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ù)媒體查詢條件檢測設(shè)備的狀態(tài),這對于響應(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 讓你可以檢測某個(gè)元素是否可見,并且可以執(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)頁設(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)聽元素的尺寸變化,這對于響應(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 類似,但數(shù)據(jù)僅在會(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="用戶名" />
<div>當(dāng)前用戶: {{ user.name }}</div>
</div>
</template>
21. useElementBounding
useElementBounding 可以獲取一個(gè)元素的邊界信息(比如位置和尺寸),這對于復(fù)雜布局和動(dòng)畫效果很有幫助。
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 允許你檢測用戶是否在線,這在處理離線狀態(tài)和數(shù)據(jù)同步時(shí)非常有用。
import { useOnline } from '@vueuse/core';
export default {
setup() {
const isOnline = useOnline();
return { isOnline };
},
};
//在模板中顯示在線狀態(tài):
<template>
<div>
<div>網(wǎng)絡(luò)狀態(tài): {{ isOnline ? '在線' : '離線' }}</div>
</div>
</template>
23. usePreferredLanguages
usePreferredLanguages 可以獲取用戶的首選語言列表,這在多語言支持的應(yīng)用中非常有用。
import { usePreferredLanguages } from '@vueuse/core';
export default {
setup() {
const preferredLanguages = usePreferredLanguages();
return { preferredLanguages };
},
};
//在模板中顯示首選語言:
<template>
<div>
<div>首選語言: {{ preferredLanguages.join(', ') }}</div>
</div>
</template>
總結(jié)
通過本文對 @vueuse/core 的詳細(xì)介紹,我們可以看到這個(gè)工具庫為 Vue 3 項(xiàng)目帶來了眾多便捷和強(qiáng)大的功能,大大簡化了開發(fā)過程。無論是狀態(tài)管理、設(shè)備信息獲取還是瀏覽器 API 集成,@vueuse/core 都提供了完善的解決方案,幫助開發(fā)者實(shí)現(xiàn)高效、優(yōu)雅的代碼。在實(shí)際項(xiàng)目中,充分利用這些工具不僅能提升開發(fā)效率,還能優(yōu)化用戶體驗(yàn)。
到此這篇關(guān)于23個(gè)不可錯(cuò)過的Vue3實(shí)用Hook的文章就介紹到這了,更多相關(guān)Vue3實(shí)用Hook內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Vue3 Element Plus el-tabs數(shù)據(jù)刷新實(shí)現(xiàn)方式
這篇文章主要介紹了Vue3 Element Plus el-tabs數(shù)據(jù)刷新實(shí)現(xiàn)方式,具有很好的參考價(jià)值,希望對大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2025-07-07
html頁面引入vue組件之http-vue-loader.js解讀
這篇文章主要介紹了html頁面引入vue組件之http-vue-loader.js解讀,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-04-04
Vue params傳參刷新網(wǎng)頁數(shù)據(jù)丟失的解決方法
本文討論了在Vue中實(shí)現(xiàn)刷新網(wǎng)頁不丟失數(shù)據(jù)同時(shí)隱藏URL參數(shù)的方法,通過結(jié)合瀏覽器刷新不觸發(fā)生命周期函數(shù)和使用localStorage或sessionStorage技術(shù),解決了刷新丟失數(shù)據(jù)的問題,同時(shí)介紹了Vue Router中的props屬性的應(yīng)用場景與方法,需要的朋友可以參考下2026-04-04
vue.js中父組件調(diào)用子組件的內(nèi)部方法示例
這篇文章主要給大家介紹了關(guān)于vue.js中父組件調(diào)用子組件內(nèi)部方法的相關(guān)資料,文中給出來了詳細(xì)的示例代碼供大家參考學(xué)習(xí),對大家的學(xué)習(xí)或者工作具有一定的參考價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧。2017-10-10
解決error?Couldn‘t?find?a?package.json?file?in報(bào)錯(cuò)的問題
文章介紹了npm依賴包緩存導(dǎo)致重復(fù)下載的問題,提供了刪除node_modules、清除緩存或重啟項(xiàng)目的解決方法,并附帶了查看npm緩存位置的命令2026-03-03
Element-UI中<el-cascader?/>回顯失敗問題的完美解決
我們在使用el-cascader控件往數(shù)據(jù)庫保存的都是最后一級的數(shù)據(jù),那如果再次編輯此條數(shù)據(jù)時(shí),直接給el-cascader傳入最后一級的數(shù)據(jù),它是不會(huì)自動(dòng)勾選的,下面這篇文章主要給大家介紹了關(guān)于Element-UI中<el-cascader?/>回顯失敗問題的完美解決辦法,需要的朋友可以參考下2023-01-01

