主题
syncRefs
使目标引用与源引用保持同步
¥Keep target refs in sync with a source ref
示例
用法
¥Usage
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
与多个目标同步
¥Sync with multiple targets
你还可以传递一组引用来同步。
¥You can also pass an array of refs to sync.
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
监视选项
¥Watch options
syncRefs
的选项与 watch
的 WatchOptions
类似,但默认值不同。
¥The options for syncRefs
are similar to watch
's WatchOptions
but with different default values.
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' }
时,目标参考将在渲染开始前在 当前 "tick" 的结束 处更新。
¥When setting { flush: 'pre' }
, the target reference will be updated at the end of the current "tick" before rendering starts.
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