コンテンツにスキップ

syncRefs

カテゴリ
エクスポートサイズ
158 B
最終変更
先週
関連

ターゲットのrefをソースのrefと同期させます

デモ

使い方

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

const source = ref('hello')
const target = ref('target')

const stop = syncRefs(source, target)

console.log(target.value) // hello

source.value = 'foo'

console.log(target.value) // foo

複数のターゲットとの同期

同期するrefの配列を渡すこともできます。

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

const source = ref('hello')
const target1 = ref('target1')
const target2 = ref('target2')

const stop = syncRefs(source, [target1, target2])

console.log(target1.value) // hello
console.log(target2.value) // hello

source.value = 'foo'

console.log(target1.value) // foo
console.log(target2.value) // foo

監視オプション

syncRefs のオプションは watchWatchOptions に似ていますが、デフォルト値が異なります。

ts
export interface SyncRefOptions {
  /**
   * Timing for syncing, same as watch's flush option
   *
   * @default 'sync'
   */
  flush?: WatchOptions['flush']
  /**
   * Watch deeply
   *
   * @default false
   */
  deep?: boolean
  /**
   * Sync values immediately
   *
   * @default true
   */
  immediate?: boolean
}
js
export {}

{ flush: 'pre' } を設定すると、ターゲットの参照は、レンダリングが開始される前の 現在の「チック」の終了時 に更新されます。

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

const source = ref('hello')
const target = ref('target')

syncRefs(source, target, { flush: 'pre' })

console.log(target.value) // hello

source.value = 'foo'

console.log(target.value) // hello <- still unchanged, because of flush 'pre'

await nextTick()

console.log(target.value) // foo <- changed!

型宣言

typescript
export interface SyncRefsOptions extends ConfigurableFlushSync {
  /**
   * Watch deeply
   *
   * @default false
   */
  deep?: boolean
  /**
   * Sync values immediately
   *
   * @default true
   */
  immediate?: boolean
}
/**
 * Keep target ref(s) in sync with the source ref
 *
 * @param source source ref
 * @param targets
 */
export declare function syncRefs<T>(
  source: WatchSource<T>,
  targets: Ref<T> | Ref<T>[],
  options?: SyncRefsOptions,
): WatchHandle

ソース

ソースデモドキュメント

貢献者

Anthony Fu
Anthony Fu
Nozomu Ikuta
sun0day
Bruno Perel

変更履歴

v12.0.0-beta.1 2024/11/21
0a9ed - feat!: Vue 2 のサポートを削除、バンドルを最適化、クリーンアップ (#4349)

MITライセンスの下でリリースされています。