1. 程式人生 > 程式設計 >5個可以加速開發的VueUse函式庫(小結)

5個可以加速開發的VueUse函式庫(小結)

目錄
  • Use 有哪些實用程式?
  • 將 VueUse 安裝到你的 Vue 專案中
  • 1、useRefHistory 跟蹤響應式資料的更改
  • 2、onClickOutside 關閉模態
  • 3、useVModel 簡化了 v-model 繫結
  • 4、使用InterpObserver 跟蹤元素可見性
  • 5、useTransition 在值之間緩和
  • 最後的想法

VueUse 是 Anthony Fu 的一個開源專案,它為 Vue 開發人員提供了大量適用於 Vue 2 和 Vue 3 的基本 Composition API 實用程式函式。

5個可以加速開發的VueUse函式庫(小結)

它為常見的開發人員用例提供了數十種解決方案,例如,跟蹤引用更改、檢測元素可見性、簡化常見的 Vue 模式、鍵盤/滑鼠輸入等。這是真正節省開發時間的好方法,因為你不必自己新增所有這些標準功能。

我喜歡 VueUse 庫,因為在決定提供哪些實用程式時,它確實將開發人員放在首位,而且它是一個維護良好的庫,因為它與當前版本的 Vue 保持同步。

VueUse 有哪些實用程式?

如果你想檢視每個實用程式www.cppcns.com的完整列表,我絕對建議你檢視官方文件。但總結一下,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:qaPHQiDm//unpkg.com/@vueuse/shaqaPHQiDmred"></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,redo } = useRefHistory(text)
</script>

<style scoped>
  button {
    border: none;
    outline: none;
    margin-right: 10px;
    background-color: #2ecc71;
    color: white;
    padding: 5px 10px;;
  }
</style>

好的,現在讓我們執行它。當我們輸入時,每個字元都會觸發歷史陣列中的一個新條目,如果我們單擊撤消/重做,我們將轉到相應的條目。

5個可以加速開發的VueUse函式庫(小結)

還有不同的選項可以為此功能新增更多功能。例如,我們可以深入跟蹤反應物件並限制這樣的歷史條目的數量。

const { history,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>

結果是這樣的,我們可以用我們的按鈕開啟彈出視窗,然後通過在彈出內容視窗外單擊來關閉它。

5個可以加速開發的VueUse函式庫(小結)

3、useVModel 簡化了 v-model 繫結

Vue 開發人員的一個常見用例是為元件建立自定義 v-model 繫結。這意味著我們的元件接受一個值作為 prop,並且每當該值被修改時,我們的元件都會向父級發出更新事件。

5個可以加速開發的VueUse函式庫(小結)

有關構建自定義 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
    }
  }
}

結果看起來像這樣,我們在父級中的值始終與子級中的輸入保持同步。

5個可以加速開發的VueUse函式庫(小結)

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>

當我們執行它並滾動時,我們會看到它正確更新。

5個可以加速開發的VueUse函式庫(小結)

我們還可以為 Interp Observer 指定更多選項,例如,更改其根元素、邊距(用於計算交點的根邊界框的偏移量)和閾值級別。

//useInterpObserver 的選項
const { stop } = useInterpObserver(
      target,{
// root,rootMargin,threshold,window
// full options in the source: https://.com/vueuse/vueuse/blob/main/packages/core/useInterpObserver/index.ts
        threshold: 0.5,}
)

同樣重要的是看到這個方法返回一個stop函式,我們可以呼叫它來停止觀察交叉點。如果我們只想跟蹤元素第一次在螢幕上可見時,這尤其有用。

在此程式碼片段中,一旦targetIsVisible設定為 true,觀察者將停止,即使我們滾動離開目標元素,我們的值仍將保持為 true。

//停止 InterpObserver
const { stop } = useInterpObserver(
      target,observerElement) => {
        targetIsVisible.value = isIntersecting
        if (isIntersecting) {
          stop()
        }
      },)

5、useTransition 在值之間緩和

useTransition是整個 VueUse 庫中我最喜歡的函式之一。它允許我們在一行中平滑地在數值之間緩和。

我們有一個儲存為 ref 的數字源和一個輸出,它將是不同值之間的緩和。例如,假設我們要為 Vue 3 備忘單構建一個類似於註冊頁面上的計數器。

5個可以加速開發的VueUse函式庫(小結)

我們可以通過三個步驟來做到這一點:

  • 建立我們的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(sourqaPHQiDmce,})
source.value = 5000
</script>

結果如下!

5個可以加速開發的VueUse函式庫(小結)

我們還可以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,})
const color = computed(() => {
const [r,g,b] = output.value
return `rgb(${r},${g},${b})`
})
source.value = [255,255]
</script>

5個可以加速開發的VueUse函式庫(小結)

我們還可以採用一些很酷的方法來進一步定製它,可以使用任何內建的過渡預設或使用 緩動功能定義,這個可以自行決定。

最後的想法

這絕不是 VueUse的完整指南。這些只是我發現 VueUse許多函式中最有趣的一些函式而已。

我喜歡所有這些實用函式,它可以幫助我們加速開發專案,提升開發效率,因為它們中的每一個都是為了解決特定但常見的用例而設計的。

到此這篇關於5個可以加速開發的VueUse函式庫的文章就介紹到這了,更多相關VueUse 函式庫內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!