5 個(gè)可以加速開發(fā)的 VueUse 函數(shù)庫(kù)

VueUse 有哪些實(shí)用程序?
Animation——包含易于使用的過渡、超時(shí)和計(jì)時(shí)功能。 Browser——可用于不同的屏幕控制、剪貼板、偏好等。 Component——提供了不同組件方法的簡(jiǎn)寫。 Formatters——提供響應(yīng)時(shí)間格式化功能。 Sensors——用來監(jiān)聽不同的DOM事件、輸入事件和網(wǎng)絡(luò)事件。 State——管理用戶狀態(tài)(全局、本地存儲(chǔ)、會(huì)話存儲(chǔ))。 Utility——不同的實(shí)用函數(shù),如 getter、條件、引用同步等。 Watch——更多高級(jí)類型的觀察器,如可暫停的觀察器、退避的觀察器和條件觀察器。 Misc——不同類型的事件、WebSockets和web workers 的功能
將 VueUse 安裝到你的 Vue 項(xiàng)目中
npm i @vueuse/core # yarn add @vueuse/core
我建議使用NPM,因?yàn)樗褂梅ǜ菀桌斫?,但如果我們使用CDN,VueUse將在應(yīng)用程序中通過 window.VueUse 訪問。
對(duì)于NPM的安裝,所有的功能都可以通過使用標(biāo)準(zhǔn)的對(duì)象重構(gòu)從 @vueuse/core 中導(dǎo)入,像這樣訪問。
import { useRefHistory } from ‘/core’
好了,現(xiàn)在我們已經(jīng)安裝了VueUse,讓我們?cè)趹?yīng)用程序中使用它!
useRefHistory 跟蹤響應(yīng)式數(shù)據(jù)的更改
useRefHistory 跟蹤對(duì)Ref所做的每一個(gè)改變,并將其存儲(chǔ)在一個(gè)數(shù)組中。這使我們能夠輕松地為我們的應(yīng)用程序提供撤銷和重做功能。
讓我們看一個(gè)示例,其中我們正在構(gòu)建一個(gè)我們希望能夠撤消的文本區(qū)域。
第一步是在不使用 VueUse 的情況下創(chuàng)建我們的基本組件——使用 ref、textarea 和用于撤消和重做的按鈕。
<template><p><button> Undo </button><button> Redo </button></p><textarea v-model="text"/></template><script setup>import { ref } from 'vue'const text = ref('')</script><style scoped>button {border: none;outline: none;margin-right: 10px;background-color: #2ecc71;color: white;padding: 5px 10px;;}</style>
然后,讓我們通過導(dǎo)入 useRefHistory 函數(shù),然后從我們的文本 ref 中提取history、undo 和 redo 屬性來添加 VueUse。這就像調(diào)用 useRefHistory 并傳遞我們的 ref 一樣簡(jiǎn)單。
import { ref } from 'vue'import { useRefHistory } from '@vueuse/core'const text = ref('')const { history, undo, redo } = useRefHistory(text)
每次我們的 ref 更改時(shí),這都會(huì)觸發(fā)一個(gè)觀察者——更新我們剛剛創(chuàng)建的 history 屬性。
然后,為了讓我們能真正看到發(fā)生了什么,讓我們打印出模板內(nèi)的歷史記錄,同時(shí)在點(diǎn)擊相應(yīng)的按鈕時(shí)調(diào)用我們的 undo 和 redo 函數(shù)。
<template><p><button @click="undo"> Undo </button><button @click="redo"> Redo </button></p><textarea v-model="text"/><ul><li v-for="entry in history" :key="entry.timestamp">{{ entry }}</li></ul></template><script setup>import { ref } from 'vue'import { useRefHistory } from '@vueuse/core'const text = ref('')const { history, undo, redo } = useRefHistory(text)</script><style scoped>button {border: none;outline: none;margin-right: 10px;background-color: #2ecc71;color: white;padding: 5px 10px;;}</style>
好的,讓我們運(yùn)行它。當(dāng)我們輸入時(shí),每個(gè)字符都會(huì)觸發(fā)歷史數(shù)組中的一個(gè)新條目,如果我們點(diǎn)擊undo/redo,我們會(huì)轉(zhuǎn)到相應(yīng)的條目。
還有不同的選項(xiàng)可以為此功能添加更多功能。例如,我們可以深入跟蹤反應(yīng)對(duì)象并限制這樣的歷史條目的數(shù)量。
const { history, undo, redo } = useRefHistory(text, {deep: true,capacity: 10,})
有關(guān)完整的選項(xiàng)清單,請(qǐng)務(wù)必查看文檔。
onClickOutside 關(guān)閉模態(tài)
onClickOutside 檢測(cè)在一個(gè)元素之外的任何點(diǎn)擊。根據(jù)我的經(jīng)驗(yàn),這個(gè)功能最常見的使用情況是關(guān)閉任何模式或彈出窗口。
通常情況下,我們希望我們的模態(tài)擋住網(wǎng)頁(yè)的其他部分,以吸引用戶的注意力并限制錯(cuò)誤。然而,如果他們真的點(diǎn)擊了模態(tài)之外的內(nèi)容,我們希望它能夠關(guān)閉。
只需兩個(gè)步驟即可完成此操作:
為我們要檢測(cè)的元素創(chuàng)建一個(gè)模板引用
使用此模板引用運(yùn)行 onClickOutside
這是一個(gè)使用 onClickOutside 的帶有彈出窗口的簡(jiǎn)單組件。
<template><button @click="open = true"> Open Popup </button><div class="popup" v-if='open'><div class="popup-content" ref="popup">Lorem ipsum dolor sit amet consectetur adipisicing elit. Corporis aliquid autem reiciendis eius accusamus sequi, ipsam corrupti vel laboriosam necessitatibus sit natus vero sint ullam! Omnis commodi eos accusantium illum?</div></div></template><script setup>import { ref } from 'vue'import { onClickOutside } from '@vueuse/core'const open = ref(false) // state of our popupconst popup = ref() // template ref// whenever our popup exists, and we click anything BUT itonClickOutside(popup, () => {open.value = false})</script><style scoped>button {border: none;outline: none;margin-right: 10px;background-color: #2ecc71;color: white;padding: 5px 10px;;}.popup {position: fixed;top: ;left: ;width: 100vw;height: 100vh;display: flex;align-items: center;justify-content: center;background: rgba(, , , 0.1);}.popup-content {min-width: 300px;padding: 20px;width: 30%;background: #fff;}</style>
結(jié)果是這樣的,我們可以用我們的按鈕打開彈出窗口,然后在彈出內(nèi)容窗口外點(diǎn)擊關(guān)閉它。
useVModel 簡(jiǎn)化了 v-model 綁定
Vue 開發(fā)人員的一個(gè)常見用例是為組件創(chuàng)建自定義 v-model 綁定。這意味著我們的組件接受一個(gè)值作為 prop,并且每當(dāng)該值被修改時(shí),我們的組件都會(huì)向父級(jí)發(fā)出更新事件。
useVModel函數(shù)將其簡(jiǎn)化為只使用標(biāo)準(zhǔn)的 ref 語法。假設(shè)我們有一個(gè)自定義的文本輸入,試圖為其文本輸入的值創(chuàng)建一個(gè) v-model。
通常情況下,我們必須接受一個(gè)值的prop,然后emit一個(gè)變化事件來更新父組件中的數(shù)據(jù)值。
我們可以使用useVModel,把它當(dāng)作一個(gè)普通的ref,而不是使用ref并調(diào)用 props.value 和 update:value。這有助于減少我們需要記住的不同語法的數(shù)量!
<template><div><inputtype="text":value="data"@input="update"/></div></template><script>import { useVModel } from '@vueuse/core'export default {props: ['data'],setup(props, { emit }) {const data = useVModel(props, 'data', emit)console.log(data.value) // equal to props.datadata.value = 'name' // equal to emit('update:data', 'name')const update = (event) => {data.value = event.target.value}return {data,update}},}</script>
每當(dāng)我們需要訪問我們的值時(shí),我們只需調(diào)用 .value,useVModel將從我們的組件props中給我們提供值。
而每當(dāng)我們改變對(duì)象的值時(shí),useVModel會(huì)向父組件發(fā)出一個(gè)更新事件。
下面是一個(gè)快速的例子,說明該父級(jí)組件可能是什么樣子…
<template><div><p> {{ data }} </p><custom-input:data="data"@update:data="data = $event"/></div></template><script>import CustomInput from './components/CustomInput.vue'import { ref } from 'vue'export default {components: {CustomInput,},setup () {const data = ref('hello')return {data}}}
結(jié)果看起來像這樣,我們?cè)诟讣?jí)中的值始終與子級(jí)中的輸入保持同步。
使用IntersectionObserver 跟蹤元素可見性
在確定兩個(gè)元素是否重疊時(shí),Intersection Observers 非常強(qiáng)大。一個(gè)很好的用例是檢查元素當(dāng)前是否在視口中可見。
本質(zhì)上,它檢查目標(biāo)元素與根元素/文檔相交的百分比。如果該百分比超過某個(gè)閾值,它會(huì)調(diào)用一個(gè)回調(diào)來確定目標(biāo)元素是否可見。
useIntersectionObserver 提供了一個(gè)簡(jiǎn)單的語法來使用IntersectionObserver API。我們所需要做的就是為我們想要檢查的元素提供一個(gè)模板ref。
默認(rèn)情況下,IntersectionObserver將以文檔的視口為根基,閾值為0.1——所以當(dāng)這個(gè)閾值在任何一個(gè)方向被越過時(shí),我們的交集觀察器將被觸發(fā)。
這個(gè)例子的代碼可能是這樣的:我們有一個(gè)假的段落,只是在我們的視口中占據(jù)了空間,我們的目標(biāo)元素,然后是一個(gè)打印語句,打印我們?cè)氐目梢娦浴?/span>
<template><p> Is target visible? {{ targetIsVisible }} </p><div class="container"><div class="target" ref="target"><h1>Hello world</h1></div></div></template><script>import { ref } from 'vue'import { useIntersectionObserver } from '@vueuse/core'export default {setup() {const target = ref(null)const targetIsVisible = ref(false)const { stop } = useIntersectionObserver(target,([{ isIntersecting }], observerElement) => {targetIsVisible.value = isIntersecting},)return {target,targetIsVisible,}},}</script><style scoped>.container {width: 80%;margin: auto;background-color: #fafafa;max-height: 300px;overflow: scroll;}.target {margin-top: 500px;background-color: #1abc9c;color: white;padding: 20px;}</style>
當(dāng)我們運(yùn)行并滾動(dòng)它時(shí),我們會(huì)看到它正確地更新了。
我們還可以為 Intersection Observer 指定更多選項(xiàng),例如更改其根元素、邊距(用于計(jì)算交點(diǎn)的根邊界框的偏移量)和閾值級(jí)別。
const { stop } = useIntersectionObserver(target,([{ isIntersecting }], observerElement) => {targetIsVisible.value = isIntersecting},{// root, rootMargin, threshold, window// full options in the source: https://github.com/vueuse/vueuse/blob/main/packages/core/useIntersectionObserver/index.tsthreshold: 0.5,})
同樣重要的是,這個(gè)方法返回一個(gè) stop 函數(shù),我們可以調(diào)用這個(gè)函數(shù)來停止觀察交叉點(diǎn)。如果我們只想追蹤一個(gè)元素在屏幕上第一次可見的時(shí)候,這就特別有用。
在這段代碼中,一旦 targetIsVisible 被設(shè)置為 true,觀察者就會(huì)停止,即使我們滾動(dòng)離開目標(biāo)元素,我們的值也會(huì)保持為true。
const { stop } = useIntersectionObserver(target,([{ isIntersecting }], observerElement) => {targetIsVisible.value = isIntersectingif (isIntersecting) {stop()}},)
useTransition 在值之間過渡
useTransition 是整個(gè)veuse庫(kù)中我最喜歡的函數(shù)之一。它允許我們?cè)谝恍袃?nèi)平滑地轉(zhuǎn)換數(shù)值。我們有一個(gè)存儲(chǔ)為ref的數(shù)字源和一個(gè)將在不同數(shù)值之間緩和的輸出。例如,假設(shè)我們想建立一個(gè)計(jì)數(shù)器
我們可以通過三個(gè)步驟來做到這一點(diǎn):
創(chuàng)建我們的 count ref并將其初始化為零
使用 useTransition 創(chuàng)建 output ref(設(shè)置持續(xù)時(shí)間和轉(zhuǎn)換類型)
更改 count 的值
<script setup>import { ref } from 'vue'import { useTransition, TransitionPresets } from '@vueuse/core'const source = ref(0)const output = useTransition(source, {duration: 3000,transition: TransitionPresets.easeoutExpo,})source.value = 5000</script>
然后,在我們的模板中,我們希望顯示 output 的值,因?yàn)樗梢栽诓煌抵g平滑過渡。
<template><h2><p> Join over </p><p> {{ Math.round(output) }}+ </p><p>Developers </p></h2></template><script setup>import { ref } from 'vue'import { useTransition, TransitionPresets } from '@vueuse/core'const source = ref()const output = useTransition(source, {duration: 3000,transition: TransitionPresets.easeoutExpo,})source.value = 5000</script>
這就是結(jié)果!
我們還可以使用 useTransition 來過渡整個(gè)數(shù)字?jǐn)?shù)組,這在處理位置或顏色時(shí)很有用。處理顏色的一個(gè)絕招是使用一個(gè)計(jì)算屬性將RGB值格式化為正確的顏色語法。
<template><h2 :style="{ color: color } "> COLOR CHANGING </h2></template><script setup>import { ref, computed } from 'vue'import { useTransition, TransitionPresets } from '@vueuse/core'const source = ref([, , ])const output = useTransition(source, {duration: 3000,transition: TransitionPresets.easeOutExpo,})const color = computed(() => {const [r, g, b] = output.valuereturn `rgb(${r}, ${g}, $)`})source.value = [255, , 255]</script>
一些進(jìn)一步定制的酷方法是使用任何內(nèi)置的過渡預(yù)設(shè)或使用css緩動(dòng)函數(shù)來定義我們自己的過渡。
學(xué)習(xí)更多技能
請(qǐng)點(diǎn)擊下方公眾號(hào)
![]()

