5個適用于組合式 API 超實用的 VueUse 庫函數!
英文 | https://learnvue.co/2021/07/5-vueuse-library-functions-that-can-speed-up-development/

VueUse 有哪些實用程序?
動畫(Animation)—包含易于使用的過渡、超時和計時函數 瀏覽器(Browser)—可用于不同的屏幕控制、剪貼板、首選項等 組件(Component)— 為不同的組件方法提供簡寫 Formatters – 提供反應時間格式化功能 傳感器(Sensors )—用于監(jiān)聽不同的 DOM 事件、輸入事件和網絡事件 狀態(tài)(State )—管理用戶狀態(tài)(全局、本地存儲、會話存儲) 實用程序(Utility)—不同的實用程序函數,如 getter、條件、引用同步等 Watch —更高級的觀察者類型,如可暫停觀察者、去抖動觀察者和條件觀察者 雜項(Misc)— 事件、WebSockets 和 Web Worker 的不同類型的功能
將 VueUse 安裝到你的 Vue 項目中
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使用標準對象解構導入它們來訪問,如下所示:
// 從 VueUse 導入的示例import { useRefHistory } from '@vueuse/core'
好的。現(xiàn)在我們已經安裝了 VueUse,讓我們在我們的應用程序中使用它。
1、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函數然后從我們的文本引用中提取歷史、撤消和重做屬性來添加 VueUse 。這就像調用useRefHistory和傳遞我們的 ref一樣簡單。
import { ref } from 'vue'import { useRefHistory } from '@vueuse/core'const text = ref('')const { history, undo, redo } = useRefHistory(text)
每次我們的 ref 更改時,這都會觸發(fā)一個觀察者——更新history我們剛剛創(chuàng)建的屬性。
然后,為了讓我們真正了解發(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>
好的,現(xiàn)在讓我們運行它。當我們輸入時,每個字符都會觸發(fā)歷史數組中的一個新條目,如果我們單擊撤消/重做,我們將轉到相應的條目。

還有不同的選項可以為此功能添加更多功能。例如,我們可以深入跟蹤反應對象并限制這樣的歷史條目的數量。
//高級選項const { history, undo, redo } = useRefHistory(text, {deep: true,capacity: 10,})
如需完整的選項列表,請務必查看文檔。
2、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 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>
結果是這樣的,我們可以用我們的按鈕打開彈出窗口,然后通過在彈出內容窗口外單擊來關閉它。

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

有關構建自定義 v-model 的完整教程,請查看我們關于該主題的完整指南。
useVModel 函數將其簡化為僅使用標準 ref 語法。假設我們有一個自定義文本輸入,它試圖為其文本輸入的值創(chuàng)建一個 v-model。通常,我們必須接受該值的 prop,然后發(fā)出更改事件以更新父組件中的數據值。
我們可以像普通的 ref 一樣使用和對待它,而不是使用 ref 和調用props.value and !這有助于減少我們需要記住的不同語法的數量!update:valueuseVModel
<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>
每當我們需要訪問我們的值時,我們只需調用.valueuseVModel 就會從我們的組件 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}}}
結果看起來像這樣,我們在父級中的值始終與子級中的輸入保持同步。

4、使用IntersectionObserver 跟蹤元素可見性
在確定兩個元素是否重疊時,Intersection Observers非常強大。一個很好的用例是檢查元素當前是否在視口中可見。
本質上,它檢查目標元素與根元素/文檔相交的百分比。如果該百分比超過某個閾值,它會調用一個回調來確定目標元素是否可見。
useIntersectionObserver提供使用 IntersectionObserver API 的簡單語法。我們需要做的就是為我們要檢查的元素提供一個模板引用。
默認情況下,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 指定更多選項,例如,更改其根元素、邊距(用于計算交點的根邊界框的偏移量)和閾值級別。
//useIntersectionObserver 的選項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,})
同樣重要的是看到這個方法返回一個stop函數,我們可以調用它來停止觀察交叉點。如果我們只想跟蹤元素第一次在屏幕上可見時,這尤其有用。
在此代碼片段中,一旦targetIsVisible設置為 true,觀察者將停止,即使我們滾動離開目標元素,我們的值仍將保持為 true。
//停止 IntersectionObserverconst { stop } = useIntersectionObserver(target,([{ isIntersecting }], observerElement) => {targetIsVisible.value = isIntersectingif (isIntersecting) {stop()}},)
5、useTransition 在值之間緩和
useTransition是整個 VueUse 庫中我最喜歡的函數之一。它允許我們在一行中平滑地在數值之間緩和。
我們有一個存儲為 ref 的數字源和一個輸出,它將是不同值之間的緩和。例如,假設我們要為 Vue 3 備忘單構建一個類似于注冊頁面上的計數器。

我們可以通過三個步驟來做到這一點:
創(chuàng)建我們的countref 并將其初始化為零
創(chuàng)建我們的output參考useTransition(設置我們的持續(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.valuereturn `rgb(${r}, ${g}, $)`})source.value = [255, , 255]</script>

我們還可以采用一些很酷的方法來進一步定制它,可以使用任何內置的過渡預設或使用 CSS 緩動功能定義,這個可以自行決定。
最后的想法
這絕不是 VueUse的完整指南。這些只是我發(fā)現(xiàn) VueUse許多函數中最有趣的一些函數而已。
我喜歡所有這些實用函數,它可以幫助我們加速開發(fā)項目,提升開發(fā)效率,因為它們中的每一個都是為了解決特定但常見的用例而設計的。
我很想聽聽你是如何在自己的項目中實施 VueUse。歡迎你留下精彩的評論,我們一起交流學習。
最后,祝編程快樂!
最后
如果你覺得這篇內容對你挺有啟發(fā),我想邀請你幫我三個小忙:
點個「在看」,讓更多的人也能看到這篇內容(喜歡不點在看,都是耍流氓 -_-)
歡迎加我微信「 sherlocked_93 」拉你進技術群,長期交流學習...
關注公眾號「前端下午茶」,持續(xù)為你推送精選好文,也可以加我為好友,隨時聊騷。

