VueUse 是 Anthony Fu 的一個開源項目,它為 Vue 開發人員提供了大量適用於 Vue 2 和 Vue 3 的基本 Composition API 實用程序函數。
它為常見的開發人員用例提供了數十種解決方案,例如,跟蹤引用更改、檢測元素可見性、簡化常見的 Vue 模式、鍵盤/鼠標輸入等。這是真正節省開發時間的好方法,因為你不必自己添加所有這些標准功能。
我喜歡 VueUse 庫,因為在決定提供哪些實用程序時,它確實將開發人員放在首位,而且它是一個維護良好的庫,因為它與當前版本的 Vue 保持同步。
VueUse 有哪些實用程序?
如果你想查看每個實用程序的完整列表,我絕對建議你查看官方文檔。但總結一下,VueUse 中有 9 種函數。
-
動畫(Animation)—包含易於使用的過渡、超時和計時函數
-
瀏覽器(Browser)—可用於不同的屏幕控制、剪貼板、首選項等
-
組件(Component)— 為不同的組件方法提供簡寫
-
Formatters – 提供反應時間格式化功能
-
傳感器(Sensors )—用於監聽不同的 DOM 事件、輸入事件和網絡事件
-
狀態(State )—管理用戶狀態(全局、本地存儲、會話存儲)
-
實用程序(Utility)—不同的實用程序函數,如 getter、條件、引用同步等
-
Watch —更高級的觀察者類型,如可暫停觀察者、去抖動觀察者和條件觀察者
-
雜項(Misc)— 事件、WebSockets 和 Web Worker 的不同類型的功能
這些類別中的大多數都包含幾個不同的功能,因此 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使用標准對象解構導入它們來訪問,如下所示:
// 從 VueUse 導入的示例
import { useRefHistory } from '@vueuse/core'
好的。現在我們已經安裝了 VueUse,讓我們在我們的應用程序中使用它。
1、useRefHistory 跟蹤響應式數據的更改
useRefHistory跟蹤對 ref 所做的每個更改並將其存儲在數組中。這使我們可以輕松地為我們的應用程序提供撤消和重做功能。
讓我們看一個示例,其中我們正在構建一個我們希望能夠撤消的文本區域。
第一步是在不使用 VueUse 的情況下創建我們的基本組件——使用 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 更改時,這都會觸發一個觀察者——更新history我們剛剛創建的屬性。
然后,為了讓我們真正了解發生了什么,讓我們在模板中打印歷史記錄,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>
好的,現在讓我們運行它。當我們輸入時,每個字符都會觸發歷史數組中的一個新條目,如果我們單擊撤消/重做,我們將轉到相應的條目。
還有不同的選項可以為此功能添加更多功能。例如,我們可以深入跟蹤反應對象並限制這樣的歷史條目的數量。
//高級選項
const { history, undo, redo } = useRefHistory(text, {
deep: true,
capacity: 10,
})
如需完整的選項列表,請務必查看文檔。
2、onClickOutside 關閉模態
onClickOutside檢測在元素之外進行的任何點擊。根據我的經驗,此功能最常見的用例是關閉任何模式或彈出窗口。
通常,我們希望模態屏蔽網頁的其余部分以吸引用戶的注意力並限制錯誤。但是,如果他們確實在模態之外單擊,我們希望它關閉。
只需兩個步驟即可完成此操作:
-
為我們要檢測的元素創建一個模板引用
-
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>
結果是這樣的,我們可以用我們的按鈕打開彈出窗口,然后通過在彈出內容窗口外單擊來關閉它。
3、useVModel 簡化了 v-model 綁定
Vue 開發人員的一個常見用例是為組件創建自定義 v-model 綁定。這意味着我們的組件接受一個值作為 prop,並且每當該值被修改時,我們的組件都會向父級發出更新事件。
有關構建自定義 v-model 的完整教程,請查看我們關於該主題的完整指南。
useVModel 函數將其簡化為僅使用標准 ref 語法。假設我們有一個自定義文本輸入,它試圖為其文本輸入的值創建一個 v-model。通常,我們必須接受該值的 prop,然后發出更改事件以更新父組件中的數據值。
我們可以像普通的 ref 一樣使用和對待它,而不是使用 ref 和調用props.value and !這有助於減少我們需要記住的不同語法的數量!update:valueuseVModel
<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>
每當我們需要訪問我們的值時,我們只需調用.valueuseVModel 就會從我們的組件 props 中獲取值。每當我們更改對象的值時,useVModel 都會向父組件發出更新事件。
這是父組件可能是什么樣子的一個快速示例......
<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、使用InterpObserver 跟蹤元素可見性
在確定兩個元素是否重疊時,Interp Observers非常強大。一個很好的用例是檢查元素當前是否在視口中可見。
本質上,它檢查目標元素與根元素/文檔相交的百分比。如果該百分比超過某個閾值,它會調用一個回調來確定目標元素是否可見。
useInterpObserver提供使用 InterpObserver API 的簡單語法。我們需要做的就是為我們要檢查的元素提供一個模板引用。
默認情況下,InterpObserver 將使用文檔的視口作為根,閾值為 0.1——因此當在任一方向超過該閾值時,我們的交叉觀察者將觸發。
該示例的代碼可能看起來像這樣,其中我們有一個虛擬段落,它只占用視口、目標元素中的空間。
<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 { useInterpObserver } from '@vueuse/core'
export default {
setup() {
const target = ref(null)
const targetIsVisible = ref(false)
const { stop } = useInterpObserver(
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>
當我們運行它並滾動時,我們會看到它正確更新。
我們還可以為 Interp Observer 指定更多選項,例如,更改其根元素、邊距(用於計算交點的根邊界框的偏移量)和閾值級別。
//useInterpObserver 的選項
const { stop } = useInterpObserver(
target,
([{ isIntersecting }], observerElement) => {
targetIsVisible.value = isIntersecting
},
{
// root, rootMargin, threshold, window
// full options in the source: https://github.com/vueuse/vueuse/blob/main/packages/core/useInterpObserver/index.ts
threshold: 0.5,
}
)
同樣重要的是看到這個方法返回一個stop函數,我們可以調用它來停止觀察交叉點。如果我們只想跟蹤元素第一次在屏幕上可見時,這尤其有用。
在此代碼片段中,一旦targetIsVisible設置為 true,觀察者將停止,即使我們滾動離開目標元素,我們的值仍將保持為 true。
//停止 InterpObserver
const { stop } = useInterpObserver(
target,
([{ isIntersecting }], observerElement) => {
targetIsVisible.value = isIntersecting
if (isIntersecting) {
stop()
}
},
)
5、useTransition 在值之間緩和
useTransition是整個 VueUse 庫中我最喜歡的函數之一。它允許我們在一行中平滑地在數值之間緩和。
我們有一個存儲為 ref 的數字源和一個輸出,它將是不同值之間的緩和。例如,假設我們要為 Vue 3 備忘單構建一個類似於注冊頁面上的計數器。
我們可以通過三個步驟來做到這一點:
-
創建我們的countref 並將其初始化為零
-
創建我們的output參考useTransition(設置我們的持續時間和轉換類型)
-
改變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}, ${b})`
})
source.value = [255, , 255]
</script>
我們還可以采用一些很酷的方法來進一步定制它,可以使用任何內置的過渡預設或使用 CSS 緩動功能定義,這個可以自行決定。