跳到主要内容

syncRefs

分类
导出大小
198 字节
上次更改
8 个月前
相关

使目标 ref 与源 ref 保持同步

演示

用法

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

与多个目标同步

你也可以传入一个 ref 数组进行同步。

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 {
  /**
   * Timing for syncing, same as watch's flush option
   *
   * @default 'sync'
   */
  
flush
?:
WatchOptionFlush
/** * Watch deeply * * @default false */
deep
?: boolean
/** * Sync values immediately * * @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 <- still unchanged, because of flush 'pre'
await
nextTick
()
console
.
log
(
target
.
value
) // foo <- changed!

类型声明

ts
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
Arthur Darkstone
IlyaL
我想静静
Nozomu Ikuta
sun0day
Bruno Perel

更新日志

v12.3.0
021d0 - feat(toArray): 新的实用函数 (#4432)
0a9ed - feat!: 放弃对 Vue 2 的支持,优化打包并清理 (#4349)

根据 MIT 许可证发布。