5 個可以加速開發(fā)的 VueUse 庫函數

VueUse 是 Anthony Fu 的一個開源項目,它為 Vue 開發(fā)人員提供了大量適用于 Vue 2 和 Vue 3 的基本 Composition API 實用程序函數。
它有幾十個解決方案,適用于常見的開發(fā)者用例,如跟蹤Ref變化、檢測元素可見性、簡化常見的Vue模式、鍵盤/鼠標輸入等。這是一個真正節(jié)省開發(fā)時間的好方法,因為你不必自己添加所有這些標準功能。
我喜歡VueUse庫,因為它在決定提供哪些實用工具時真正把開發(fā)者放在第一位,而且它是一個維護良好的庫,因為它與Vue的當前版本保持同步。
VueUse 有哪些實用程序?
如果你想看到每一個實用程序的完整列表,我絕對建議你去看看官方文檔[1]。但總結一下,VueUse中有9種類型的函數。
Animation——包含易于使用的過渡、超時和計時功能。 Browser——可用于不同的屏幕控制、剪貼板、偏好等。 Component——提供了不同組件方法的簡寫。 Formatters——提供響應時間格式化功能。 Sensors——用來監(jiān)聽不同的DOM事件、輸入事件和網絡事件。 State——管理用戶狀態(tài)(全局、本地存儲、會話存儲)。 Utility——不同的實用函數,如 getter、條件、引用同步等。 Watch——更多高級類型的觀察器,如可暫停的觀察器、退避的觀察器和條件觀察器。 Misc——不同類型的事件、WebSockets和web workers 的功能
這些類別中的大多數都包含幾個不同的功能,所以VueUse對于你的使用情況來說是很靈活的,可以作為一個很好的地方來快速開始構建Vue應用程序。
在本教程中,我們將看一下5個不同的VueUse函數,這樣你就可以了解在這個庫中工作是多么容易。
但首先,讓我們將其添加到Vue項目中!
將 VueUse 安裝到你的 Vue 項目中
VueUse的最大特點之一是,它只用一個軟件包就能同時兼容Vue 2和Vue 3!
安裝VueUse有兩種選擇npm或CDN
npm i @vueuse/core # yarn add @vueuse/core
<script src="https://unpkg.com/@vueuse/shared"></script>
<script src="https://unpkg.com/@vueuse/core"></script>
我建議使用NPM,因為它使用法更容易理解,但如果我們使用CDN,VueUse將在應用程序中通過 window.VueUse 訪問。
對于NPM的安裝,所有的功能都可以通過使用標準的對象重構從 @vueuse/core 中導入,像這樣訪問。
import { useRefHistory } from '@vueuse/core'
好了,現在我們已經安裝了VueUse,讓我們在應用程序中使用它!
useRefHistory 跟蹤響應式數據的更改
useRefHistory 跟蹤對Ref所做的每一個改變,并將其存儲在一個數組中。這使我們能夠輕松地為我們的應用程序提供撤銷和重做功能。
讓我們看一個示例,其中我們正在構建一個我們希望能夠撤消的文本區(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>
然后,讓我們通過導入 useRefHistory 函數,然后從我們的文本 ref 中提取history、undo 和 redo 屬性來添加 VueUse。這就像調用 useRefHistory 并傳遞我們的 ref 一樣簡單。
import { ref } from 'vue'
import { useRefHistory } from '@vueuse/core'
const text = ref('')
const { history, undo, redo } = useRefHistory(text)
每次我們的 ref 更改時,這都會觸發(fā)一個觀察者——更新我們剛剛創(chuàng)建的 history 屬性。
然后,為了讓我們能真正看到發(fā)生了什么,讓我們打印出模板內的歷史記錄,同時在點擊相應的按鈕時調用我們的 undo 和 redo 函數。
<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>
好的,讓我們運行它。當我們輸入時,每個字符都會觸發(fā)歷史數組中的一個新條目,如果我們點擊undo/redo,我們會轉到相應的條目。

還有不同的選項可以為此功能添加更多功能。例如,我們可以深入跟蹤反應對象并限制這樣的歷史條目的數量。
const { history, undo, redo } = useRefHistory(text, {
deep: true,
capacity: 10,
})
有關完整的選項清單,請務必查看文檔。
onClickOutside 關閉模態(tài)
onClickOutside 檢測在一個元素之外的任何點擊。根據我的經驗,這個功能最常見的使用情況是關閉任何模式或彈出窗口。
通常情況下,我們希望我們的模態(tài)擋住網頁的其他部分,以吸引用戶的注意力并限制錯誤。然而,如果他們真的點擊了模態(tài)之外的內容,我們希望它能夠關閉。
只需兩個步驟即可完成此操作:
為我們要檢測的元素創(chuàng)建一個模板引用 使用此模板引用運行 onClickOutside
這是一個使用 onClickOutside 的帶有彈出窗口的簡單組件。
<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 popup
const popup = ref() // template ref
// whenever our popup exists, and we click anything BUT it
onClickOutside(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>
結果是這樣的,我們可以用我們的按鈕打開彈出窗口,然后在彈出內容窗口外點擊關閉它。

useVModel 簡化了 v-model 綁定
Vue 開發(fā)人員的一個常見用例是為組件創(chuàng)建自定義 v-model 綁定。這意味著我們的組件接受一個值作為 prop,并且每當該值被修改時,我們的組件都會向父級發(fā)出更新事件。

useVModel函數將其簡化為只使用標準的 ref 語法。假設我們有一個自定義的文本輸入,試圖為其文本輸入的值創(chuàng)建一個 v-model。通常情況下,我們必須接受一個值的prop,然后emit一個變化事件來更新父組件中的數據值。
我們可以使用useVModel,把它當作一個普通的ref,而不是使用ref并調用 props.value 和 update:value。這有助于減少我們需要記住的不同語法的數量!
<template>
<div>
<input
type="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.data
data.value = 'name' // equal to emit('update:data', 'name')
const update = (event) => {
data.value = event.target.value
}
return {
data,
update
}
},
}
</script>
每當我們需要訪問我們的值時,我們只需調用 .value,useVModel將從我們的組件props中給我們提供值。而每當我們改變對象的值時,useVModel會向父組件發(fā)出一個更新事件。
下面是一個快速的例子,說明該父級組件可能是什么樣子...
<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
}
}
}
結果看起來像這樣,我們在父級中的值始終與子級中的輸入保持同步。

使用IntersectionObserver 跟蹤元素可見性
在確定兩個元素是否重疊時,Intersection Observers [2] 非常強大。一個很好的用例是檢查元素當前是否在視口中可見。
本質上,它檢查目標元素與根元素/文檔相交的百分比。如果該百分比超過某個閾值,它會調用一個回調來確定目標元素是否可見。
useIntersectionObserver 提供了一個簡單的語法來使用IntersectionObserver API。我們所需要做的就是為我們想要檢查的元素提供一個模板ref。默認情況下,IntersectionObserver將以文檔的視口為根基,閾值為0.1——所以當這個閾值在任何一個方向被越過時,我們的交集觀察器將被觸發(fā)。
這個例子的代碼可能是這樣的:我們有一個假的段落,只是在我們的視口中占據了空間,我們的目標元素,然后是一個打印語句,打印我們元素的可見性。
<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>
當我們運行并滾動它時,我們會看到它正確地更新了。

我們還可以為 Intersection Observer 指定更多選項,例如更改其根元素、邊距(用于計算交點的根邊界框的偏移量)和閾值級別。
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.ts
threshold: 0.5,
}
)
同樣重要的是,這個方法返回一個 stop 函數,我們可以調用這個函數來停止觀察交叉點。如果我們只想追蹤一個元素在屏幕上第一次可見的時候,這就特別有用。
在這段代碼中,一旦 targetIsVisible 被設置為 true,觀察者就會停止,即使我們滾動離開目標元素,我們的值也會保持為true。
const { stop } = useIntersectionObserver(
target,
([{ isIntersecting }], observerElement) => {
targetIsVisible.value = isIntersecting
if (isIntersecting) {
stop()
}
},
)
useTransition 在值之間過渡
useTransition 是整個veuse庫中我最喜歡的函數之一。它允許我們在一行內平滑地轉換數值。
我們有一個存儲為ref的數字源和一個將在不同數值之間緩和的輸出。例如,假設我們想建立一個計數器

我們可以通過三個步驟來做到這一點:
創(chuàng)建我們的 countref并將其初始化為零使用 useTransition創(chuàng)建outputref(設置持續(xù)時間和轉換類型)更改 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 的值,因為它可以在不同值之間平滑過渡。
<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>
這就是結果!

我們還可以使用 useTransition 來過渡整個數字數組,這在處理位置或顏色時很有用。處理顏色的一個絕招是使用一個計算屬性將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.value
return `rgb(${r}, ${g}, $)`
})
source.value = [255, , 255]
</script>

一些進一步定制的酷方法是使用任何內置的過渡預設或使用CSS緩動函數來定義我們自己的過渡。
最后的想法
這絕不是 VueUse 的完整指南,這些只是我發(fā)現 VueUse 庫中最有趣的許多函數。
我喜歡所有這些實用功能對加快開發(fā)速度的幫助,因為它們中的每一個都是為了解決具體而又常見的用例。
我很想聽聽你是如何在自己的項目中實施VueUse的。請在下面留下任何評論。
原文:https://learnvue.co/2021/07/5-vueuse-library-functions-that-can-speed-up-development/
作者:Matt Maribojoc
最近文章
參考資料
官方文檔: https://vueuse.org/functions.html
[2]Intersection Observers : https://developer.mozilla.org/en-US/docs/Web/API/IntersectionObserver
