VueUse 是 Anthony Fu 的一個開源項目,它為 Vue 開發(fā)人員提供了大量適用于 Vue 2 和 Vue 3 的基本 Composition API 實用程序函數(shù)。本篇文章就來給大家分享幾個我常用的幾個 VueUse 最佳組合,希望對大家有所幫助!
(學(xué)習(xí)視頻分享:vue視頻教程)
Vueuse擁有大量出色的組合。但是量太大,要把它們?nèi)靠赐昕赡軙屓俗ゲ坏街攸c。下面來介紹一些有用到的組合,它們?nèi)缦拢?/p>
-
onClickOutside
-
useFocusTrap
-
useHead
-
useStorage
-
useVModel
-
useImage
-
useDark
1、 onClickOutside
檢測點擊非常簡單。但是,當(dāng)點擊發(fā)生在一個元素之外時,如何檢測?那就有點棘手了。但使用VueUse中的 onClickOutside 組件就很容易能做到這點。代碼如下:
<script setup> import { ref } from 'vue' import { onClickOutside } from '@vueuse/core' const container = ref(null) onClickOutside(container, () => alert('Good. Better to click outside.')) </script> <template> <div> <p>Hey there, here's some text.</p> <div class="container" ref="container"> <p>Please don't click in here.</p> </div> </div> </template>
為想要追蹤的 container
元素創(chuàng)建一個 ref
:
const container = ref(null);
然后我們用元素上的ref
屬性把它變成一個模板ref
。
<div class="container" ref="container"> <p>Please don't click in here.</p> </div>
有了容器的ref
之后,我們把它和一個處理程序一起傳遞給onClickOutside
組合。
onClickOutside( container, () => alert('Good. Better to click outside.') )
這種可組合對于管理窗口或下拉菜單很有用。當(dāng)用戶點擊下拉菜單以外的地方時,你可以關(guān)閉它。
模態(tài)框也通常表現(xiàn)出這種行為。
事例地址:https://stackblitz.com/edit/vue3-script-setup-with-vite-18scsl?file=src%2FApp.vue
2、useFocusTrap
為了擁有可訪問的應(yīng)用程序,正確地管理焦點非常重要。
沒有什么比不小心在模態(tài)后面加tab,并且無法將焦點返回到模態(tài)更糟糕的了。這就是焦點陷阱的作用。
將鍵盤焦點鎖定在一個特定的DOM元素上,不是在整個頁面中循環(huán),而是在瀏覽器本身中循環(huán),鍵盤焦點只在該DOM元素中循環(huán)。
下面是一個使用VueUse的useFocusTrap
的例子:
<script setup> import { ref } from 'vue' import { useFocusTrap } from '@vueuse/integrations/useFocusTrap' const container = ref(null) useFocusTrap(container, { immediate: true }) </script> <template> <div> <button tab-index="-1">Can't click me</button> <div class="container" ref="container"> <button tab-index="-1">Inside the trap</button> <button tab-index="-1">Can't break out</button> <button tab-index="-1">Stuck here forever</button> </div> <button tab-index="-1">Can't click me</button> </div> </template>
將immediate
設(shè)置為true
,頁面加載時,焦點將被放置在 container
元素中。然后,就不可能在該容器之外的地方做標(biāo)簽。
到達(dá)第三個按鈕后,再次點擊tab
鍵將回到第一個按鈕。
就像onClickOutside
一樣,我們首先為 container
設(shè)置了模板ref
。
const container = ref(null)
<div class="container" ref="container"> <button tab-index="-1">Inside the trap</button> <button tab-index="-1">Can't break out</button> <button tab-index="-1">Stuck here forever</button> </div>
然后我們把這個模板引用傳遞給useFocusTrap
組合。
useFocusTrap(container, { immediate: true });
immediate
選項將自動把焦點設(shè)置到容器內(nèi)第一個可關(guān)注的元素上。
事例地址:https://stackblitz.com/edit/vue3-script-setup-with-vite-eocc6w?file=src%2FApp.vue
3、useHead
VueUse為我們提供了一種簡單的方法來更新我們應(yīng)用程序的 head 部分–頁面 title、scripts和其他可能放在這里的的東西。
useHead 組合要求我們首先設(shè)置一個插件
import { createApp } from 'vue' import { createHead } from '@vueuse/head' import App from './App.vue' const app = createApp(App) const head = createHead() app.use(head) app.mount('#app')
一旦我們使用了這個插件,我們就可以隨心所欲地更新標(biāo)題部分。在這個例子中,我們將在一個按鈕上注入一些自定義樣式。
<script setup> import { ref } from 'vue' import { useHead } from '@vueuse/head' const styles = ref('') useHead({ // Inject a style tag into the head style: [{ children: styles }], }) const injectStyles = () => { styles.value = 'button { background: red }' } </script> <template> <div> <button @click="injectStyles">Inject new styles</button> </div> </template>
首先,我們創(chuàng)建一個ref
來表示我們要注入的樣式,默認(rèn)為空:
const styles = ref('');
第二,設(shè)置 useHead
將樣式注入到頁面中。
useHead({ // Inject a style tag into the head style: [{ children: styles }], })
然后,添加注入這些樣式的方法:
const injectStyles = () => { styles.value = 'button { background: red }' }
當(dāng)然,我們并不局限于注入樣式。我們可以在我們的<head>
中添加任何這些內(nèi)容:
-
title
-
meta tags
-
link tags
-
base tag
-
style tags
-
script tags
-
html attributes
-
body attributes
事例地址:https://stackblitz.com/edit/vue3-script-setup-with-vite-szhedp?file=src%2FApp.vue
4、useStorage
useStorage
真的很酷,因為它會自動將 ref
同步到 localstorage,事例如下:
<script setup> import { useStorage } from '@vueuse/core' const input = useStorage('unique-key', 'Hello, world!') </script> <template> <div> <input v-model="input" /> </div> </template>
第一次加載時, input
顯示 'Hello, world!',但最后,它會顯示你最后在 input
中輸入的內(nèi)容,因為它被保存在localstorage中。
除了 localstorage,我們也可以指定 sessionstorage
:
const input = useStorage('unique-key', 'Hello, world!', sessionStorage)
當(dāng)然,也可以自己實現(xiàn)存儲系統(tǒng),只要它實現(xiàn)了StorageLike
接口。
export interface StorageLike { getItem(key: string): string | null setItem(key: string, value: string): void removeItem(key: string): void }
5、useVModel
v-model
指令是很好的語法糖,使雙向數(shù)據(jù)綁定更容易。
但useVModel
更進(jìn)一步,擺脫了一堆沒有人真正想寫的模板代碼。
<script setup> import { useVModel } from '@vueuse/core' const props = defineProps({ count: Number, }) const emit = defineEmits(['update:count']) const count = useVModel(props, 'count', emit) </script> <template> <div> <button @click="count = count - 1">-</button> <button @click="count = 0">Reset to 0</button> <button @click="count = count + 1">+</button> </div> </template>
在這個例子中,我們首先定義了要附加到v-model
上的 props:
const props = defineProps({ count: Number, })
然后我們發(fā)出一個事件,使用v-model
的命名慣例update:<propName>
:
const emit = defineEmits(['update:count'])
現(xiàn)在,我們可以使用useVModel
組合來將 prop
和事件綁定到一個ref
。
const count = useVModel(props, 'count', emit)
每當(dāng) prop 發(fā)生變化時,這個 count
就會改變。但只要它從這個組件中被改變,它就會發(fā)出update:count
事件,通過v-model
指令觸發(fā)更新。
我們可以像這樣使用這個 Input
組件。
<script setup> import { ref } from 'vue' import Input from './components/Input.vue' const count = ref(50) </script> <template> <div> <Input v-model:count="count" /> {{ count }} </div> </template>
這里的count ref
是通過v-model
綁定與 Input
組件內(nèi)部的count ref
同步的。
事例地址:https://stackblitz.com/edit/vue3-script-setup-with-vite-ut5ap8?file=src%2FApp.vue
6、useImage
隨著時間的推移,web應(yīng)用中的圖像變得越來越漂亮。我們已經(jīng)有了帶有srcset
的響應(yīng)式圖像,漸進(jìn)式加載庫,以及只有在圖像滾動到視口時才會加載的庫。
但你知道嗎,我們也可以訪問圖像本身的加載和錯誤狀態(tài)?
我以前主要通過監(jiān)聽每個HTML元素發(fā)出的onload
和onerror
事件來做到這一點,但VueUse給我們提供了一個更簡單的方法,那就是useImage
組合。
<script setup> import { useImage } from '@vueuse/core' // Change this to a non-existent URL to see the error state const url = 'https://source.unsplash.com/random/400x300' const { isLoading, error } = useImage( { src: url, }, { // Just to show the loading effect more clearly delay: 2000, } ) </script> <template> <div> <div v-if="isLoading" class="loading gradient"></div> <div v-else-if="error">Couldn't load the image :(</div> <img v-else :src="url" /> </div> </template>
第一步,通過useImage
設(shè)置圖片的src
:
const { isLoading, error } = useImage({ src: url })
獲取它返回的isLoading
和error
引用,以便跟蹤狀態(tài)。這個組合在內(nèi)部使用useAsyncState
,因此它返回的值與該組合的值相同。
安排好后,useImage
就會加載我們的圖像并將事件處理程序附加到它上面。
我們所要做的就是在我們的模板中使用相同的URL來使用該圖片。由于瀏覽器會重復(fù)使用任何緩存的圖片,它將重復(fù)使用由useImage
加載的圖片。
<template> <div> <div v-if="isLoading" class="loading gradient"></div> <div v-else-if="error">Couldn't load the image :(</div> <img v-else :src="url" /> </div> </template>
在這里,我們設(shè)置了一個基本的加載和錯誤狀態(tài)處理程序。當(dāng)圖片正在加載時,我們顯示一個帶有動畫漸變的占位符。如果有錯誤,我們顯示一個錯誤信息。否則我們可以渲染圖像。
UseImage 還有其他一些很棒的特性!如果想讓它成為響應(yīng)式圖像,那么它支持srcset
和sizes
屬性,這些屬性在幕后傳遞給img
元素。
如果你想把所有內(nèi)容都放在模板中,還有一個無渲染組件。它的工作原理與組合的相同:
<template> <UseImage src="https://source.unsplash.com/random/401x301"> <template #loading> <div class="loading gradient"></div> </template> <template #error> Oops! </template> </UseImage> </template>
事例:https://stackblitz.com/edit/vue3-script-setup-with-vite-d1jsec?file=src%2FApp.vue
7、暗黑模式 useDark
最近,每個網(wǎng)站和應(yīng)用程序似乎都有暗黑模式。最難的部分是造型的改變。但是一旦你有了這些,來回切換就很簡單了。
如果你使用的是Tailwind,你只需要在html元素中添加dark類,就可以在整個頁面中啟用。
<html class="dark"><!-- ... --></html>
然而,在黑暗模式和光明模式之間切換時,有幾件事需要考慮。首先,我們要考慮到用戶的系統(tǒng)設(shè)置。第二,我們要記住他們是否已經(jīng)推翻了這個選擇。
VueUse的useDark
組合性為我們把所有這些東西都包起來。默認(rèn)情況下,它查看系統(tǒng)設(shè)置,但任何變化都會被持久化到localStorage
,所以設(shè)置會被記住。
<script setup> import { useDark, useToggle } from '@vueuse/core' const isDark = useDark() const toggleDark = useToggle(isDark) </script> <template> <div class="container"> Changes with dark/light mode. <button @click="toggleDark()"> Enable {{ isDark ? 'Light' : 'Dark' }} Mode </button> </div> </template>
黑暗模式的樣式:
.dark .container { background: slategrey; color: white; border-color: black; } .dark button { background: lightgrey; color: black; } .dark body { background: darkgrey; }
如果你沒有使用Tailwind,你可以通過傳入一個選項對象來完全定制黑暗模式的應(yīng)用方式。下面是默認(rèn)的Tailwind:
const isDark = useDark({ selector: 'html', attribute: 'class', valueDark: 'dark', valueLight: '', })
也可以提供一個onChanged處理程序,這樣你就可以編寫任何你需要的Javascript。這兩種方法使你可以使它與你已有的任何造型系統(tǒng)一起工作。
總結(jié)
Vueuse 擁有一個巨大的庫,其中包含出色的組合,而我們在這里只涵蓋了其中的一小部分。我強(qiáng)烈建議你花些時間去探索這些文檔,看看所有可用的東西。這是一個非常好的資源,它將使你免于大量的模板代碼和不斷地重新發(fā)明車輪。
【相關(guān)視頻教程推薦:vuejs入門教程、web前端入門】