五個(gè)可以加速開(kāi)發(fā)的 VueUse 庫(kù)函數(shù)
VueUse 是 Anthony Fu 的一個(gè)開(kāi)源項(xiàng)目,它為 Vue 開(kāi)發(fā)人員提供了大量適用于 Vue 2 和 Vue 3 的基本 Composition API 實(shí)用程序函數(shù)。
它有幾十個(gè)解決方案,適用于常見(jiàn)的開(kāi)發(fā)者用例,如跟蹤Ref變化、檢測(cè)元素可見(jiàn)性、簡(jiǎn)化常見(jiàn)的Vue模式、鍵盤(pán)/鼠標(biāo)輸入等。這是一個(gè)真正節(jié)省開(kāi)發(fā)時(shí)間的好方法,因?yàn)槟悴槐刈约禾砑铀羞@些標(biāo)準(zhǔn)功能。
我喜歡VueUse庫(kù),因?yàn)樗跊Q定提供哪些實(shí)用工具時(shí)真正把開(kāi)發(fā)者放在第一位,而且它是一個(gè)維護(hù)良好的庫(kù),因?yàn)樗cVue的當(dāng)前版本保持同步。
VueUse 有哪些實(shí)用程序?
如果你想看到每一個(gè)實(shí)用程序的完整列表,我絕對(duì)建議你去看看官方文檔[1]。但總結(jié)一下,VueUse中有9種類(lèi)型的函數(shù)。
- Animation——包含易于使用的過(guò)渡、超時(shí)和計(jì)時(shí)功能。
- Browser——可用于不同的屏幕控制、剪貼板、偏好等。
- Component——提供了不同組件方法的簡(jiǎn)寫(xiě)。
- Formatters——提供響應(yīng)時(shí)間格式化功能。
- Sensors——用來(lái)監(jiān)聽(tīng)不同的DOM事件、輸入事件和網(wǎng)絡(luò)事件。
- State——管理用戶狀態(tài)(全局、本地存儲(chǔ)、會(huì)話存儲(chǔ))。
- Utility——不同的實(shí)用函數(shù),如 getter、條件、引用同步等。
- Watch——更多高級(jí)類(lèi)型的觀察器,如可暫停的觀察器、退避的觀察器和條件觀察器。
- Misc——不同類(lèi)型的事件、WebSockets和web workers 的功能
這些類(lèi)別中的大多數(shù)都包含幾個(gè)不同的功能,所以VueUse對(duì)于你的使用情況來(lái)說(shuō)是很靈活的,可以作為一個(gè)很好的地方來(lái)快速開(kāi)始構(gòu)建Vue應(yīng)用程序。
在本教程中,我們將看一下5個(gè)不同的VueUse函數(shù),這樣你就可以了解在這個(gè)庫(kù)中工作是多么容易。
但首先,讓我們將其添加到Vue項(xiàng)目中!
將 VueUse 安裝到你的 Vue 項(xiàng)目中
VueUse的最大特點(diǎn)之一是,它只用一個(gè)軟件包就能同時(shí)兼容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,因?yàn)樗褂梅ǜ菀桌斫猓绻覀兪褂肅DN,VueUse將在應(yīng)用程序中通過(guò) window.VueUse 訪問(wèn)。
對(duì)于NPM的安裝,所有的功能都可以通過(guò)使用標(biāo)準(zhǔn)的對(duì)象重構(gòu)從 @vueuse/core 中導(dǎo)入,像這樣訪問(wèn)。
- import { useRefHistory } from '@vueuse/core'
好了,現(xiàn)在我們已經(jīng)安裝了VueUse,讓我們?cè)趹?yīng)用程序中使用它!
useRefHistory 跟蹤響應(yīng)式數(shù)據(jù)的更改
useRefHistory 跟蹤對(duì)Ref所做的每一個(gè)改變,并將其存儲(chǔ)在一個(gè)數(shù)組中。這使我們能夠輕松地為我們的應(yīng)用程序提供撤銷(xiāo)和重做功能。
讓我們看一個(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>
然后,讓我們通過(guò)導(dǎo)入 useRefHistory 函數(shù),然后從我們的文本 ref 中提取history、undo 和 redo 屬性來(lái)添加 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è)功能最常見(jiàn)的使用情況是關(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 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>
結(jié)果是這樣的,我們可以用我們的按鈕打開(kāi)彈出窗口,然后在彈出內(nèi)容窗口外點(diǎn)擊關(guān)閉它。
useVModel 簡(jiǎn)化了 v-model 綁定
Vue 開(kāi)發(fā)人員的一個(gè)常見(jiàn)用例是為組件創(chuàng)建自定義 v-model 綁定。這意味著我們的組件接受一個(gè)值作為 prop,并且每當(dāng)該值被修改時(shí),我們的組件都會(huì)向父級(jí)發(fā)出更新事件。
useVModel函數(shù)將其簡(jiǎn)化為只使用標(biāo)準(zhǔn)的 ref 語(yǔ)法。假設(shè)我們有一個(gè)自定義的文本輸入,試圖為其文本輸入的值創(chuàng)建一個(gè) v-model。通常情況下,我們必須接受一個(gè)值的prop,然后emit一個(gè)變化事件來(lái)更新父組件中的數(shù)據(jù)值。
我們可以使用useVModel,把它當(dāng)作一個(gè)普通的ref,而不是使用ref并調(diào)用 props.value 和 update:value。這有助于減少我們需要記住的不同語(yǔ)法的數(shù)量!
- <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>
每當(dāng)我們需要訪問(wèn)我們的值時(shí),我們只需調(diào)用 .value,useVModel將從我們的組件props中給我們提供值。而每當(dāng)我們改變對(duì)象的值時(shí),useVModel會(huì)向父組件發(fā)出一個(gè)更新事件。
下面是一個(gè)快速的例子,說(shuō)明該父級(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é)果看起來(lái)像這樣,我們?cè)诟讣?jí)中的值始終與子級(jí)中的輸入保持同步。
使用IntersectionObserver 跟蹤元素可見(jiàn)性
在確定兩個(gè)元素是否重疊時(shí),Intersection Observers [2] 非常強(qiáng)大。一個(gè)很好的用例是檢查元素當(dāng)前是否在視口中可見(jiàn)。
本質(zhì)上,它檢查目標(biāo)元素與根元素/文檔相交的百分比。如果該百分比超過(guò)某個(gè)閾值,它會(huì)調(diào)用一個(gè)回調(diào)來(lái)確定目標(biāo)元素是否可見(jiàn)。
useIntersectionObserver 提供了一個(gè)簡(jiǎn)單的語(yǔ)法來(lái)使用IntersectionObserver API。我們所需要做的就是為我們想要檢查的元素提供一個(gè)模板ref。默認(rèn)情況下,IntersectionObserver將以文檔的視口為根基,閾值為0.1——所以當(dāng)這個(gè)閾值在任何一個(gè)方向被越過(guò)時(shí),我們的交集觀察器將被觸發(fā)。
這個(gè)例子的代碼可能是這樣的:我們有一個(gè)假的段落,只是在我們的視口中占據(jù)了空間,我們的目標(biāo)元素,然后是一個(gè)打印語(yǔ)句,打印我們?cè)氐目梢?jiàn)性。
- <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.ts
- threshold: 0.5,
- }
- )
同樣重要的是,這個(gè)方法返回一個(gè) stop 函數(shù),我們可以調(diào)用這個(gè)函數(shù)來(lái)停止觀察交叉點(diǎn)。如果我們只想追蹤一個(gè)元素在屏幕上第一次可見(jiàn)的時(shí)候,這就特別有用。
在這段代碼中,一旦 targetIsVisible 被設(shè)置為 true,觀察者就會(huì)停止,即使我們滾動(dòng)離開(kāi)目標(biāo)元素,我們的值也會(huì)保持為true。
- const { stop } = useIntersectionObserver(
- target,
- ([{ isIntersecting }], observerElement) => {
- targetIsVisible.value = isIntersecting
- if (isIntersecting) {
- stop()
- }
- },
- )
useTransition 在值之間過(guò)渡
useTransition 是整個(gè)veuse庫(kù)中我最喜歡的函數(shù)之一。它允許我們?cè)谝恍袃?nèi)平滑地轉(zhuǎn)換數(shù)值。
我們有一個(gè)存儲(chǔ)為ref的數(shù)字源和一個(gè)將在不同數(shù)值之間緩和的輸出。例如,假設(shè)我們想建立一個(gè)計(jì)數(shù)器。
我們可以通過(guò)三個(gè)步驟來(lái)做到這一點(diǎn):
- 創(chuàng)建我們的 count ref并將其初始化為零
- 使用 useTransition 創(chuàng)建 output ref(設(shè)置持續(xù)時(shí)間和轉(zhuǎn)換類(lèi)型)
- 更改 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平滑過(guò)渡。
- <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 來(lái)過(guò)渡整個(gè)數(shù)字?jǐn)?shù)組,這在處理位置或顏色時(shí)很有用。處理顏色的一個(gè)絕招是使用一個(gè)計(jì)算屬性將RGB值格式化為正確的顏色語(yǔ)法。
- <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>
一些進(jìn)一步定制的酷方法是使用任何內(nèi)置的過(guò)渡預(yù)設(shè)或使用CSS緩動(dòng)函數(shù)來(lái)定義我們自己的過(guò)渡。
最后的想法
這絕不是 VueUse 的完整指南,這些只是我發(fā)現(xiàn) VueUse 庫(kù)中最有趣的許多函數(shù)。
我喜歡所有這些實(shí)用功能對(duì)加快開(kāi)發(fā)速度的幫助,因?yàn)樗鼈冎械拿恳粋€(gè)都是為了解決具體而又常見(jiàn)的用例。
我很想聽(tīng)聽(tīng)你是如何在自己的項(xiàng)目中實(shí)施VueUse的。請(qǐng)?jiān)谙旅媪粝氯魏卧u(píng)論。
原文:https://learnvue.co/2021/07/5-vueuse-library-functions-that-can-speed-up-development/
作者:Matt Maribojoc
參考資料
[1]官方文檔: https://vueuse.org/functions.html
[2]Intersection Observers : https://developer.mozilla.org/en-US/docs/Web/API/IntersectionObserver
本文轉(zhuǎn)載自微信公眾號(hào)「前端全棧開(kāi)發(fā)者」,可以通過(guò)以下二維碼關(guān)注。轉(zhuǎn)載本文請(qǐng)聯(lián)系前端全棧開(kāi)發(fā)者公眾號(hào)。