- 資訊首頁(yè) > 開(kāi)發(fā)技術(shù) >
- 好用的VueUse函數有哪些
小編給大家分享一下好用的VueUse函數有哪些,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!
VueUse是Anthony Fu大佬的一個(gè)開(kāi)源項目,它為Vue的開(kāi)發(fā)者提供了大量用于Vue2和Vue3的基本Composition API實(shí)用工具函數。
它有幾十個(gè)用于常見(jiàn)開(kāi)發(fā)人員用例的解決方案,如跟蹤ref更改,檢測元素可見(jiàn)性,簡(jiǎn)化常見(jiàn)Vue模式,鍵盤(pán)/鼠標輸入等。 這是真正節省開(kāi)發(fā)時(shí)間的好方法,因為我們不必自己親手添加所有這些標準功能,拿來(lái)主義,用就對了(再次感謝大佬的付出)。
我喜歡VueUse庫,因為它在決定提供哪些實(shí)用工具時(shí)真正把開(kāi)發(fā)者放在第一位,而且它是一個(gè)維護良好的庫,因為它與Vue的當前版本保持同步。
VueUse 有哪些實(shí)用方法?
如果你想看到每一個(gè)實(shí)用程序的完整列表,建議去看看官方文檔。但總結一下,VueUse 中有9種類(lèi)型的函數。
Animation(動(dòng)畫(huà)) - 包含易于使用的過(guò)渡、超時(shí)和計時(shí)功能
Browser (瀏覽器) - 可以用于不同的屏幕控件、剪貼板、首選項等等
Component (組件) - 為不同的組件方法提供簡(jiǎn)寫(xiě)
Sensors (傳感器)- 用來(lái)監聽(tīng)不同的DOM事件、輸入事件和網(wǎng)絡(luò )事件
State (狀態(tài)) - 管理用戶(hù)狀態(tài)(全局,本地存儲,會(huì )話(huà)存儲)
Utility (實(shí)用方法)--不同的實(shí)用方法,如getters、conditionals、ref synchronization等。
Watch --更高級的觀(guān)察器類(lèi)型,如可暫停的觀(guān)察器、放棄的觀(guān)察器和條件觀(guān)察器
其它 - 事件、WebSockets和 Web workers 的不同類(lèi)型的功能
將 Vueuse 安裝到 Vue 項目中
VueUse 的最大特點(diǎn)之一是,它只用一個(gè)包就能兼容 Vue2 和 Vue3!
安裝VueUse有兩種選擇:npm或
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/' target='_blank'>CDN, 可能通過(guò) window.VueUse 來(lái)訪(fǎng)問(wèn)。
使用 npm,可以通過(guò)解構的方式來(lái)獲得想要的方法:
import { useRefHistory } from '@vueuse/core'
useRefHistory 跟蹤響應式數據的變化
useRefHistory跟蹤對 ref 所做的每一個(gè)改變,并將其存儲在一個(gè)數組中。這樣我們能夠輕松為應用程序提供撤銷(xiāo)和重做功能。
來(lái)看一個(gè)示例,在該示例中,我們做一個(gè)能夠撤銷(xiāo)的文本區域
第一步是在沒(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>
接著(zhù),導入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)
每當我們的ref發(fā)生變化,更新history屬性時(shí),就會(huì )觸發(fā)一個(gè)監聽(tīng)器。
為了看看底層做了什么,我們把 history 內容打印出來(lái)。并在單擊相應按鈕時(shí)調用 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>
還有不同的選項,為這個(gè)功能增加更多的功能。例如,我們可以深入追蹤 reactive 對象,并像這樣限制 history 記錄的數量。
const { history, undo, redo } = useRefHistory(text, { deep: true, capacity: 10, })
onClickOutside 關(guān)閉 modal
onClickOutside 檢測在一個(gè)元素之外的任何點(diǎn)擊。根據我的經(jīng)驗,這個(gè)功能最常見(jiàn)的使用情況是關(guān)閉任何模態(tài)或彈出窗口。
通常,我們希望我們的模態(tài)屏蔽網(wǎng)頁(yè)的其余部分,以吸引用戶(hù)的注意和限制錯誤。然而,如果他們確實(shí)點(diǎn)擊了模態(tài)之外,我們希望它關(guān)閉。
要做到這一點(diǎn),只有兩個(gè)步驟。
為要檢測的元素創(chuàng )建一個(gè)模板引用
使用這個(gè)模板ref運行onClickOutside
這是一個(gè)簡(jiǎn)單的組件,使用onClickOutside彈出窗口。
<template> <button @click="open = true"> Open Popup </button> <p class="popup" v-if='open'> <p 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? </p> </p> </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 簡(jiǎn)化 v-model 的綁定。
Vue開(kāi)發(fā)者的一個(gè)常見(jiàn)用例是為一個(gè)組件創(chuàng )建一個(gè)自定義的v-model綁定。這也要求我們的組件接受一個(gè) value 作為 prop,每當這個(gè) value 被修改,我們的組件就會(huì )向父類(lèi)發(fā)出一個(gè) update 事件。
useVModel函數將其簡(jiǎn)化為只使用標準的ref語(yǔ)法。假設我們有一個(gè)自定義的文本輸入,試圖為其文本輸入的值創(chuàng )建一個(gè)v-model。通常情況下,我們必須接受一個(gè) value的 prop,然后發(fā)出一個(gè) change 事件來(lái)更新父組件中的數據值。
我們可以使用useVModel,把它當作一個(gè)普通的ref,而不是使用ref并調用props.value和update:value。這有助于減少我們需要記住的不同語(yǔ)法的數量!
<template> <p> <input type="text" :value="data" @input="update" /> </p> </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>
每當需要訪(fǎng)問(wèn)value時(shí),我們只需調用.value,useVModel將從我們的組件 props 中給我們提供值。而每當改變對象的值時(shí),useVModel 會(huì )向父組件發(fā)出一個(gè)更新事件。
下面是父組件的一個(gè)簡(jiǎn)單示例
<template> <p> <p> {{ data }} </p> <custom-input :data="data" @update:data="data = $event" /> </p> </template> <script> import CustomInput from './components/CustomInput.vue' import { ref } from 'vue' export default { components: { CustomInput, }, setup () { const data = ref('hello') return { data } } }
使用 intersectionobserver 跟蹤元素的可見(jiàn)性
當確定兩個(gè)元素是否重疊時(shí),useIntersectionObserver 是非常強大的。這方面的一個(gè)很好的用例是檢查一個(gè)元素在視口中是否當前可見(jiàn)。
基本上,它檢查目標元素與根元素/文檔相交的百分比。如果這個(gè)百分比超過(guò)了某個(gè)閾值,它就會(huì )調用一個(gè)回調,確定目標元素是否可見(jiàn)。
useIntersectionObserver提供了一個(gè)簡(jiǎn)單的語(yǔ)法來(lái)使用IntersectionObserver API。我們所需要做的就是為我們想要檢查的元素提供一個(gè)模板ref。
默認情況下,IntersectionObserver將以文檔的視口為根基,閾值為0.1--所以當這個(gè)閾值在任何一個(gè)方向被越過(guò)時(shí),我們的交集觀(guān)察器將被觸發(fā)。
示例:我們有一個(gè)假的段落,只是在我們的視口中占據了空間,目標元素,然后是一個(gè)打印語(yǔ)句,打印我們元素的可見(jiàn)性。
<template> <p> Is target visible? {{ targetIsVisible }} </p> <p class="container"> <p class="target" ref="target"> <h2>Hello world</h2> </p> </p> </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>
運行后,對應的值會(huì )更新:
我們還可以為我們的 Intersection Observer 指定更多的選項,比如改變它的根元素、邊距(計算交叉點(diǎn)時(shí)對根的邊界框的偏移)和閾值水平。
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 函數,我們可以調用這個(gè)函數來(lái)停止觀(guān)察交叉點(diǎn)。如果我們只想追蹤一個(gè)元素在屏幕上第一次可見(jiàn)的時(shí)候,這就特別有用。
在這段代碼中,一旦targetIsVisible被設置為true,observer 就會(huì )停止,即使我們滾動(dòng)離開(kāi)目標元素,我們的值也會(huì )保持為 true 。
const { stop } = useIntersectionObserver( target, ([{ isIntersecting }], observerElement) => { targetIsVisible.value = isIntersecting if (isIntersecting) { stop() } }, )
使用 useTransition 做個(gè)數字加載動(dòng)畫(huà)
useTransition是整個(gè)VueUse庫中我最喜歡的函數之一。它允許我們只用一行就能順利地在數值之間進(jìn)行過(guò)渡。
我們可以通過(guò)三個(gè)步驟來(lái)做到這一點(diǎn)。
初始化一個(gè) ref 變量 count ,初始值為 0
使用 useTransition 創(chuàng )建一個(gè)變量 output
改變 count 的值
import { ref } from 'vue' import { useTransition, TransitionPresets } from '@vueuse/core' const count = ref(0) const output = useTransition(count , { duration: 3000, transition: TransitionPresets.easeOutExpo, }) count.value = 5000 </script>
然后在 template 中顯示 output 的值:
<template> <h3> <p> Join over </p> <p> {{ Math.round(output) }}+ </p> <p>Developers </p> </h3> </template> <script setup> import { ref } from 'vue' import { useTransition, TransitionPresets } from '@vueuse/core' const count = ref(0) const output = useTransition(count, { duration: 3000, transition: TransitionPresets.easeOutExpo, }) count.value = 5000 </script>
我們還可以使用useTransition 轉換整個(gè)數字數組。 使用位置或顏色時(shí),這非常有用。 使用顏色的一個(gè)很好的技巧是使用計算的屬性將RGB值格式化為正確的顏色語(yǔ)法。
<template> <h3 :style="{ color: color } "> COLOR CHANGING </h3> </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>
免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng )、來(lái)自互聯(lián)網(wǎng)轉載和分享為主,文章觀(guān)點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權請聯(lián)系QQ:712375056 進(jìn)行舉報,并提供相關(guān)證據,一經(jīng)查實(shí),將立刻刪除涉嫌侵權內容。
Copyright ? 2009-2021 56dr.com. All Rights Reserved. 特網(wǎng)科技 特網(wǎng)云 版權所有 珠海市特網(wǎng)科技有限公司 粵ICP備16109289號
域名注冊服務(wù)機構:阿里云計算有限公司(萬(wàn)網(wǎng)) 域名服務(wù)機構:煙臺帝思普網(wǎng)絡(luò )科技有限公司(DNSPod) CDN服務(wù):阿里云計算有限公司 中國互聯(lián)網(wǎng)舉報中心 增值電信業(yè)務(wù)經(jīng)營(yíng)許可證B2
建議您使用Chrome、Firefox、Edge、IE10及以上版本和360等主流瀏覽器瀏覽本網(wǎng)站