Skip to content

syncRefs

类别
导出体积
198 B
上次更改
6 months ago
相关

将目标引用与源引用保持同步

示例

用法

ts
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

与多个目标同步

你也可以传递一个引用数组来同步。

ts
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,但具有不同的默认值。

ts
export interface SyncRefOptions {
  /**
   * 同步时机,与 watch 的 flush 选项相同
   *
   * @default 'sync'
   */
  
flush
?:
WatchOptions
['flush']
/** * 深度监视 * * @default false */
deep
?: boolean
/** * 立即同步值 * * @default true */
immediate
?: boolean
}
js
export {}

当设置 { flush: 'pre' } 时,目标引用将在渲染开始之前的当前 “tick” 结束时更新。

ts
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 <- 已更改!

类型声明

ts
export interface SyncRefsOptions extends ConfigurableFlushSync {
  /**
   * 深度监视
   *
   * @default false
   */
  
deep
?: boolean
/** * 立即同步值 * * @default true */
immediate
?: boolean
} /** * 将目标 ref 与源 ref 保持同步 * * @param source 源 ref * @param targets 目标值 */ export declare function
syncRefs
<
T
>(
source
:
WatchSource
<
T
>,
targets
:
Ref
<
T
> |
Ref
<
T
>[],
options
?: SyncRefsOptions,
):
WatchHandle

源码

源码演示文档

贡献者

Anthony Fu
一纸忘忧
Anthony Fu
IlyaL
我想静静
Nozomu Ikuta
sun0day
Bruno Perel

更新日志

021d0 - feat(toArray): new utility function (#4432)
0a9ed - feat!: drop Vue 2 support, optimize bundles and clean up (#4349)