syncRefs

syncRefs

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

使用法

import { syncRefs } from '@vueuse/core'
import { shallowRef } from 'vue'

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

const stop = syncRefs(source, target)

console.log(target.value) // hello

source.value = 'foo'

console.log(target.value) // foo

複数のターゲットと同期

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

import { syncRefs } from '@vueuse/core'
import { shallowRef } from 'vue'

const source = shallowRef('hello')
const target1 = shallowRef('target1')
const target2 = shallowRef('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 に似ていますが、デフォルト値が異なります。

export interface SyncRefOptions {
  /**
   * 同期のタイミング、watch の flush オプションと同じ
   *
   * @default 'sync'
   */
  flush?: WatchOptionFlush
  /**
   * 深くウォッチする
   *
   * @default false
   */
  deep?: boolean
  /**
   * 値を即座に同期する
   *
   * @default true
   */
  immediate?: boolean
}

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

import { syncRefs } from '@vueuse/core'
import { nextTick, shallowRef } from 'vue'

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

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

console.log(target.value) // hello

source.value = 'foo'

console.log(target.value) // hello <- まだ変更されていない、flush 'pre' のため

await nextTick()

console.log(target.value) // foo <- 変更された!