溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

VueUse使用實例分析

發(fā)布時間:2022-07-21 09:20:23 來源:億速云 閱讀:226 作者:iii 欄目:編程語言

今天小編給大家分享一下VueUse使用實例分析的相關(guān)知識點,內(nèi)容詳細,邏輯清晰,相信大部分人都還太了解這方面的知識,所以分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后有所收獲,下面我們一起來了解一下吧。

VueUse使用實例分析

Vueuse擁有大量出色的組合。但是量太大,要把它們?nèi)靠赐昕赡軙屓俗ゲ坏街攸c。下面來介紹一些有用到的組合,它們?nèi)缦拢?/p>

  • onClickOutside

  • useFocusTrap

  • useHead

  • useStorage

  • useVModel

  • useImage

  • useDark

1、 onClickOutside

VueUse使用實例分析

檢測點擊非常簡單。但是,當(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)出這種行為。

2、useFocusTrap

VueUse使用實例分析

為了擁有可訪問的應(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)簽。

到達第三個按鈕后,再次點擊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)注的元素上。

3、useHead

VueUse使用實例分析

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來表示我們要注入的樣式,默認為空:

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

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更進一步,擺脫了一堆沒有人真正想寫的模板代碼。

<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同步的。

6、useImage

VueUse使用實例分析

隨著時間的推移,web應(yīng)用中的圖像變得越來越漂亮。我們已經(jīng)有了帶有srcset的響應(yīng)式圖像,漸進式加載庫,以及只有在圖像滾動到視口時才會加載的庫。

但你知道嗎,我們也可以訪問圖像本身的加載和錯誤狀態(tài)?

我以前主要通過監(jiān)聽每個HTML元素發(fā)出的onloadonerror事件來做到這一點,但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 })

獲取它返回的isLoadingerror引用,以便跟蹤狀態(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)式圖像,那么它支持srcsetsizes屬性,這些屬性在幕后傳遞給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>

7、暗黑模式 useDark

VueUse使用實例分析

最近,每個網(wǎng)站和應(yīng)用程序似乎都有暗黑模式。最難的部分是造型的改變。但是一旦你有了這些,來回切換就很簡單了。

如果你使用的是Tailwind,你只需要在html元素中添加dark類,就可以在整個頁面中啟用。

<html class="dark"><!-- ... --></html>

然而,在黑暗模式和光明模式之間切換時,有幾件事需要考慮。首先,我們要考慮到用戶的系統(tǒng)設(shè)置。第二,我們要記住他們是否已經(jīng)推翻了這個選擇。

VueUse的useDark組合性為我們把所有這些東西都包起來。默認情況下,它查看系統(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)用方式。下面是默認的Tailwind:

const isDark = useDark({
  selector: 'html',
  attribute: 'class',
  valueDark: 'dark',
  valueLight: '',
})

也可以提供一個onChanged處理程序,這樣你就可以編寫任何你需要的Javascript。這兩種方法使你可以使它與你已有的任何造型系統(tǒng)一起工作。

以上就是“VueUse使用實例分析”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家閱讀完這篇文章都有很大的收獲,小編每天都會為大家更新不同的知識,如果還想學(xué)習(xí)更多的知識,請關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI