溫馨提示×

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

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

until封裝watch常用邏輯簡化代碼怎么寫

發(fā)布時(shí)間:2022-07-12 09:55:59 來源:億速云 閱讀:133 作者:iii 欄目:開發(fā)技術(shù)

這篇文章主要介紹“until封裝watch常用邏輯簡化代碼怎么寫”,在日常操作中,相信很多人在until封裝watch常用邏輯簡化代碼怎么寫問題上存在疑惑,小編查閱了各式資料,整理出簡單好用的操作方法,希望對(duì)大家解答”until封裝watch常用邏輯簡化代碼怎么寫”的疑惑有所幫助!接下來,請(qǐng)跟著小編一起來學(xué)習(xí)吧!

1.示例

結(jié)合文檔的介紹,筆者寫了如下的demo代碼:

<script setup lang="ts">
import { until , invoke } from '@vueuse/core'
import {ref} from 'vue'
const source = ref(0)
invoke(async () => {
  await until(source).toBe(4)
  console.log('滿足條件了')
}) 
const clickedFn = () => {
  source.value ++
}
</script>
<template>
 <div>{{source}}</div>
  <button @click="clickedFn">
    點(diǎn)擊按鈕
  </button>
</template>

如上代碼所示,規(guī)定了當(dāng)source的值為4的時(shí)候觸發(fā)執(zhí)行watch回調(diào)函數(shù)。這里使用到了invoke方法,我們之前接觸過,源碼如下

export function invoke<T>(fn: () => T): T {
  return fn()
}

給定參數(shù)fn為一個(gè)函數(shù),invoke返回函數(shù)的執(zhí)行結(jié)果。代碼運(yùn)行效果如下圖所示:

until封裝watch常用邏輯簡化代碼怎么寫

當(dāng)點(diǎn)擊次數(shù)達(dá)到4次時(shí),打印了相應(yīng)的信息。

2.源碼

until代碼較多,先看兩張預(yù)覽圖,了解一下其大概實(shí)現(xiàn):

until封裝watch常用邏輯簡化代碼怎么寫

until封裝watch常用邏輯簡化代碼怎么寫

通過以上兩張圖片我們看到until內(nèi)部定義了很多的用于判斷條件是否滿足的方法,最后返回的instance也是包含這些方法的對(duì)象。下面我們對(duì)這些方法逐個(gè)分析。

2.1 toMatch

function toMatch(
    condition: (v: any) => boolean,
    { flush = 'sync', deep = false, timeout, throwOnTimeout }: UntilToMatchOptions = {},
  ): Promise<T> {
    let stop: Function | null = null
    const watcher = new Promise<T>((resolve) => {
      stop = watch(
        r,
        (v) => {
          if (condition(v) !== isNot) {
            stop?.()
            resolve(v)
          }
        },
        {
          flush,
          deep,
          immediate: true,
        },
      )
    })
    const promises = [watcher]
    if (timeout != null) {
      promises.push(
        promiseTimeout(timeout, throwOnTimeout)
          .then(() => unref(r))
          .finally(() => stop?.()),
      )
    }
    return Promise.race(promises)
  }

在promise構(gòu)造函數(shù)的參數(shù)函數(shù)中調(diào)用watch API來監(jiān)聽數(shù)據(jù)源r 。當(dāng)數(shù)據(jù)源r的新值代入到條件condition中,使得condition為true時(shí)則調(diào)用stop停止監(jiān)聽數(shù)據(jù)源,并將promise狀態(tài)變?yōu)槌晒Α?/p>

promise放入promises數(shù)組中,如果用戶傳了timeout選項(xiàng)則promises放入調(diào)用promiseTimeout返回的promise實(shí)例。最后返回的是Promise.race的結(jié)果??匆幌聀romiseTimeout的代碼:

export function promiseTimeout(
  ms: number,
  throwOnTimeout = false,
  reason = 'Timeout',
): Promise<void> {
  return new Promise((resolve, reject) => {
    if (throwOnTimeout)
      setTimeout(() => reject(reason), ms)
    else
      setTimeout(resolve, ms)
  })
}

promiseTimeout返回了一個(gè)promise, 如果throwOnTimeout為true則過ms毫秒之后則將promise變?yōu)槭顟B(tài),否則經(jīng)過ms毫秒后調(diào)用resolve,使promise變?yōu)槌晒顟B(tài)。

2.2 toBe

function toBe<P>(value: MaybeRef<P | T>, options?: UntilToMatchOptions) {
    if (!isRef(value))
      return toMatch(v => v === value, options)
    const { flush = 'sync', deep = false, timeout, throwOnTimeout } = options ?? {}
    let stop: Function | null = null
    const watcher = new Promise<T>((resolve) => {
      stop = watch(
        [r, value],
        ([v1, v2]) => {
          if (isNot !== (v1 === v2)) {
            stop?.()
            resolve(v1)
          }
        },
        {
          flush,
          deep,
          immediate: true,
        },
      )
    })
     // 和toMatch相同部分省略
  }

toBe方法體大部分和toMatch相同,只是watch回調(diào)函數(shù)不同。這里對(duì)數(shù)據(jù)源r和toBe的參數(shù)value進(jìn)行監(jiān)聽,當(dāng)r的值和value的值相同時(shí),使promise狀態(tài)為成功。注意這里的watch使用的是偵聽多個(gè)源的情況。

2.3 toBeTruthy、toBeNull、toBeUndefined、toBeNaN

function toBeTruthy(options?: UntilToMatchOptions) {
  return toMatch(v => Boolean(v), options)
}
function toBeNull(options?: UntilToMatchOptions) {
  return toBe<null>(null, options)
}
function toBeUndefined(options?: UntilToMatchOptions) {
  return toBe<undefined>(undefined, options)
}
function toBeNaN(options?: UntilToMatchOptions) {
  return toMatch(Number.isNaN, options)
}

toBeTruthy和toBeNaN是對(duì)toMatch的封裝,toBeNull和toBeUndefined是對(duì)toBe的封裝。toBeTruthy判斷是否為真值,方法是使用Boolean構(gòu)造函數(shù)后判斷參數(shù)v是否為真值。

toBeNaN判斷是否為NAN, 使用的是Number的isNaN作為判斷條件,注意toBeNaN的實(shí)現(xiàn)不能使用toBe, 因?yàn)閠obe在做比較的時(shí)候使用的是 &lsquo;===&rsquo;這對(duì)于NaN是不成立的:

until封裝watch常用邏輯簡化代碼怎么寫

toBeNull用于判斷是否為null,toBeUndefined用于判斷是否為undefined。

2.4 toContains

function toContains(
value: any,
 options?: UntilToMatchOptions,
) {
  return toMatch((v) => {
    const array = Array.from(v as any)
    return array.includes(value) || array.includes(unref(value))
  }, options)
}

判斷數(shù)據(jù)源v中是否有value,Array.from把v轉(zhuǎn)換為數(shù)組,然后使用includes方法判斷array中是否包含value。

2.5 changed和changedTimes

function changed(options?: UntilToMatchOptions) {
  return changedTimes(1, options)
}
function changedTimes(n = 1, options?: UntilToMatchOptions) {
  let count = -1 // skip the immediate check
  return toMatch(() => {
    count += 1
    return count >= n
  }, options)
}

changed用于判斷是否改變,通過調(diào)用changedTimes和固定第一參數(shù)n為1實(shí)現(xiàn)的。changedTimes的第一個(gè)參數(shù)為監(jiān)聽的數(shù)據(jù)源改變的次數(shù),也是通過調(diào)用toMatch實(shí)現(xiàn)的,傳給toMatch的條件是一個(gè)函數(shù),此函數(shù)會(huì)在數(shù)據(jù)源改變時(shí)調(diào)用。每調(diào)用一次外層作用域定義的count就會(huì)累加一次 ,注意外層作用域count變量聲明為-1, 因?yàn)闀r(shí)立即監(jiān)聽的。

至此,until源碼內(nèi)定義的函數(shù)全部分析完畢,下圖總結(jié)了這些函數(shù)之前的調(diào)用關(guān)系:

until封裝watch常用邏輯簡化代碼怎么寫

源碼中最后的返回值也值得我們說一說。

2.6 until返回值&mdash;&mdash;instance

until的返回值分為兩種情況:當(dāng)監(jiān)聽的源數(shù)據(jù)是數(shù)組時(shí)和不是數(shù)組時(shí),代碼如下圖所示:

if (Array.isArray(unref(r))) {
  const instance: UntilArrayInstance<T> = {
    toMatch,
    toContains,
    changed,
    changedTimes,
    get not() {
      isNot = !isNot
      return this
    },
  }
  return instance
}
else {
  const instance: UntilValueInstance<T, boolean> = {
    toMatch,
    toBe,
    toBeTruthy: toBeTruthy as any,
    toBeNull: toBeNull as any,
    toBeNaN,
    toBeUndefined: toBeUndefined as any,
    changed,
    changedTimes,
    get not() {
      isNot = !isNot
      return this
    },
  }
  return instance
}

我們看到數(shù)據(jù)源時(shí)數(shù)組時(shí)返回的方法中沒有toBeTruthy,toBeNull,toBeNaN,toBeUndefined這些用于判斷基本類型值的方法。另外需要注意的是返回的instance里面有一個(gè)get not(){// ...}這是使用getters, 用于獲取特定的屬性(這里是not)。在getter里面對(duì)isNot取反,isNot返回值為this也就是instance本身,所以讀取完not屬性后可以鏈?zhǔn)秸{(diào)用其他方法,如下所示:

await until(ref).not.toBeNull()
await until(ref).not.toBeTruthy()

到此,關(guān)于“until封裝watch常用邏輯簡化代碼怎么寫”的學(xué)習(xí)就結(jié)束了,希望能夠解決大家的疑惑。理論與實(shí)踐的搭配能更好的幫助大家學(xué)習(xí),快去試試吧!若想繼續(xù)學(xué)習(xí)更多相關(guān)知識(shí),請(qǐng)繼續(xù)關(guān)注億速云網(wǎng)站,小編會(huì)繼續(xù)努力為大家?guī)砀鄬?shí)用的文章!

向AI問一下細(xì)節(jié)

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

AI