跳到主要內容

refWithControl

類別
匯出大小
402 B
上次變更
4 個月前
別名
controlledRef
相關

精細控制 ref 及其響應性。

警告

此函式僅適用於 Vue 3

用法

refWithControl 使用 extendRef 來提供兩個額外函式 getset,以便更好地控制何時應追蹤/觸發響應性。

ts
import { refWithControl } from '@vueuse/core'

const num = refWithControl(0)
const doubled = computed(() => num.value * 2)

// just like normal ref
num.value = 42
console.log(num.value) // 42
console.log(doubled.value) // 84

// set value without triggering the reactivity
num.set(30, false)
console.log(num.value) // 30
console.log(doubled.value) // 84 (doesn't update)

// get value without tracking the reactivity
watchEffect(() => {
  console.log(num.peek())
}) // 30

num.value = 50 // watch effect wouldn't be triggered since it collected nothing.
console.log(doubled.value) // 100 (updated again since it's a reactive set)

peeklayuntrackedGetsilentSet

我們也提供了一些簡寫方式,用於在不追蹤/觸發響應系統的情況下進行 get/set 操作。以下程式碼行是等效的。

ts
const foo = refWithControl('foo')
ts
// getting
foo.get(false)
foo.untrackedGet()
foo.peek() // an alias for `untrackedGet`
ts
// setting
foo.set('bar', false)
foo.silentSet('bar')
foo.lay('bar') // an alias for `silentSet`

配置

onBeforeChange()

提供 onBeforeChange 選項是為了控制是否應接受新值。例如

ts
const num = refWithControl(0, {
  onBeforeChange(value, oldValue) {
    // disallow changes larger then ±5 in one operation
    if (Math.abs(value - oldValue) > 5)
      return false // returning `false` to dismiss the change
  },
})

num.value += 1
console.log(num.value) // 1

num.value += 6
console.log(num.value) // 1 (change been dismissed)

onChanged()

onChanged 選項提供的功能與 Vue 的 watch 類似,但與 watch 相比,同步化開銷更低。

ts
const num = refWithControl(0, {
  onChanged(value, oldValue) {
    console.log(value)
  },
})

類型宣告

typescript
export interface ControlledRefOptions<T> {
  /**
   * Callback function before the ref changing.
   *
   * Returning `false` to dismiss the change.
   */
  onBeforeChange?: (value: T, oldValue: T) => void | boolean
  /**
   * Callback function after the ref changed
   *
   * This happens synchronously, with less overhead compare to `watch`
   */
  onChanged?: (value: T, oldValue: T) => void
}
/**
 * Fine-grained controls over ref and its reactivity.
 */
export declare function refWithControl<T>(
  initial: T,
  options?: ControlledRefOptions<T>,
): ShallowUnwrapRef<{
  get: (tracking?: boolean) => T
  set: (value: T, triggering?: boolean) => void
  untrackedGet: () => T
  silentSet: (v: T) => void
  peek: () => T
  lay: (v: T) => void
}> &
  Ref<T, T>
/**
 * Alias for `refWithControl`
 */
export declare const controlledRef: typeof refWithControl

原始碼

原始碼文件

貢獻者

Anthony Fu
Anthony Fu
Joscha Götzer
_Ghosteye
sun0day
vaakian X

更新日誌

v12.0.0-beta.1 於 2024/11/21
0a9ed - feat!: 移除 Vue 2 支援,最佳化 bundles 並清理 (#4349)

在 MIT 授權下發布。