VueUse是Anthony Fu大佬的一個(gè)開(kāi)源項(xiàng)目,它為Vue的開(kāi)發(fā)者提供了大量用于Vue2和Vue3的基本Composition API實(shí)用工具函數(shù)。
它有幾十個(gè)用于常見(jiàn)開(kāi)發(fā)人員用例的解決方案,如跟蹤ref更改,檢測(cè)元素可見(jiàn)性,簡(jiǎn)化常見(jiàn)Vue模式,鍵盤(pán)/鼠標(biāo)輸入等。 這是真正節(jié)省開(kāi)發(fā)時(shí)間的好方法,因?yàn)槲覀儾槐刈约河H手添加所有這些標(biāo)準(zhǔn)功能,拿來(lái)主義,用就對(duì)了(再次感謝大佬的付出)。
我喜歡VueUse庫(kù),因?yàn)樗跊Q定提供哪些實(shí)用工具時(shí)真正把開(kāi)發(fā)者放在第一位,而且它是一個(gè)維護(hù)良好的庫(kù),因?yàn)樗cVue的當(dāng)前版本保持同步。
VueUse 有哪些實(shí)用方法?
如果你想看到每一個(gè)實(shí)用程序的完整列表,建議去看看官方文檔。但總結(jié)一下,VueUse 中有9種類(lèi)型的函數(shù)。
-
Animation(動(dòng)畫(huà)) – 包含易于使用的過(guò)渡、超時(shí)和計(jì)時(shí)功能
-
Browser (瀏覽器) – 可以用于不同的屏幕控件、剪貼板、首選項(xiàng)等等
-
Component (組件) – 為不同的組件方法提供簡(jiǎn)寫(xiě)
-
Sensors (傳感器)- 用來(lái)監(jiān)聽(tīng)不同的DOM事件、輸入事件和網(wǎng)絡(luò)事件
-
State (狀態(tài)) – 管理用戶(hù)狀態(tài)(全局,本地存儲(chǔ),會(huì)話存儲(chǔ))
-
Utility (實(shí)用方法)–不同的實(shí)用方法,如getters、conditionals、ref synchronization等。
-
Watch –更高級(jí)的觀察器類(lèi)型,如可暫停的觀察器、放棄的觀察器和條件觀察器
-
其它 – 事件、WebSockets和 Web workers 的不同類(lèi)型的功能
將 Vueuse 安裝到 Vue 項(xiàng)目中
VueUse 的最大特點(diǎn)之一是,它只用一個(gè)包就能兼容 Vue2 和 Vue3!
安裝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)樗菀桌斫?,但如果我們使用CDN, 可能通過(guò) window.VueUse 來(lái)訪問(wèn)。
使用 npm,可以通過(guò)解構(gòu)的方式來(lái)獲得想要的方法:
import { useRefHistory } from '@vueuse/core'
useRefHistory 跟蹤響應(yīng)式數(shù)據(jù)的變化
useRefHistory跟蹤對(duì) ref 所做的每一個(gè)改變,并將其存儲(chǔ)在一個(gè)數(shù)組中。這樣我們能夠輕松為應(yīng)用程序提供撤銷(xiāo)和重做功能。
來(lái)看一個(gè)示例,在該示例中,我們做一個(gè)能夠撤銷(xiāo)的文本區(qū)域
第一步是在沒(méi)有 VueUse 的情況下創(chuàng)建我們的基本組件–使用ref、textarea、以及用于撤銷(xiāo)和重做的按鈕。
<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,然后通過(guò) useRefHistory從 text 中提取history、undo和redo屬性。
import { ref } from 'vue' import { useRefHistory } from '@vueuse/core' const text = ref('') const { history, undo, redo } = useRefHistory(text)
每當(dāng)我們的ref發(fā)生變化,更新history屬性時(shí),就會(huì)觸發(fā)一個(gè)監(jiān)聽(tīng)器。
為了看看底層做了什么,我們把 history 內(nèi)容打印出來(lái)。并在單擊相應(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>
還有不同的選項(xiàng),為這個(gè)功能增加