跳到主要内容

refWithControl

分类
导出大小
402 B
上次更改
上个月
别名
受控引用
相关

对 ref 及其响应性进行细粒度控制。

用法

refWithControl 使用 extendRef 提供两个额外的函数 getset,以便更好地控制何时应该跟踪/触发响应性。

ts
import { 
refWithControl
} from '@vueuse/core'
const
num
=
refWithControl
(0)
const
doubled
=
computed
(() =>
num
.
value
* 2)
// just like normal ref
num
.
value
= 42
console
.
log
(
num
.
value
) // 42
console
.
log
(
doubled
.
value
) // 84
// set value without triggering the reactivity
num
.
set
(30, false)
console
.
log
(
num
.
value
) // 30
console
.
log
(
doubled
.
value
) // 84 (doesn't update)
// get value without tracking the reactivity
watchEffect
(() => {
console
.
log
(
num
.
peek
())
}) // 30
num
.
value
= 50 // watch effect wouldn't be triggered since it collected nothing.
console
.
log
(
doubled
.
value
) // 100 (updated again since it's a reactive set)

peek, lay, untrackedGet, silentSet

我们还提供了一些简写,用于在不跟踪/触发响应系统的情况下进行获取/设置。以下行是等效的。

ts
const 
foo
=
refWithControl
('foo')
ts
// getting
foo
.
get
(false)
foo
.
untrackedGet
()
foo
.
peek
() // an alias for `untrackedGet`
ts
// setting
foo
.
set
('bar', false)
foo
.
silentSet
('bar')
foo
.
lay
('bar') // an alias for `silentSet`

配置

onBeforeChange()

提供 onBeforeChange 选项来控制是否应该接受新值。例如:

ts
const 
num
=
refWithControl
(0, {
onBeforeChange
(
value
,
oldValue
) {
// disallow changes larger then ±5 in one operation if (
Math
.
abs
(
value
-
oldValue
) > 5)
return false // returning `false` to dismiss the change }, })
num
.
value
+= 1
console
.
log
(
num
.
value
) // 1
num
.
value
+= 6
console
.
log
(
num
.
value
) // 1 (change been dismissed)

onChanged()

onChanged 选项提供了与 Vue 的 watch 类似的功能,但与 watch 相比,它是同步的且开销更小。

ts
const 
num
=
refWithControl
(0, {
onChanged
(
value
,
oldValue
) {
console
.
log
(
value
)
}, })

类型声明

ts
export interface 
ControlledRefOptions
<
T
> {
/** * Callback function before the ref changing. * * Returning `false` to dismiss the change. */
onBeforeChange
?: (
value
:
T
,
oldValue
:
T
) => void | boolean
/** * Callback function after the ref changed * * This happens synchronously, with less overhead compare to `watch` */
onChanged
?: (
value
:
T
,
oldValue
:
T
) => void
} /** * Fine-grained controls over ref and its reactivity. * * @__NO_SIDE_EFFECTS__ */ export declare function
refWithControl
<
T
>(
initial
:
T
,
options
?:
ControlledRefOptions
<
T
>,
):
ShallowUnwrapRef
<{
get
: (
tracking
?: boolean) =>
T
set
: (
value
:
T
,
triggering
?: boolean) => void
untrackedGet
: () =>
T
silentSet
: (
v
:
T
) => void
peek
: () =>
T
lay
: (
v
:
T
) => void
}> &
Ref
<
T
,
T
>
/** @deprecated use `refWithControl` instead */ export declare const
controlledRef
: typeof
refWithControl

来源

源代码文档

贡献者

Anthony Fu
Anthony Fu
SerKo
Vida Xie
David Gonzalez
Joscha Götzer
_Ghosteye
sun0day
vaakian X

更新日志

e5f74 - feat!: 弃用别名导出,转而使用原始函数名称 (#5009)
v13.6.0
d32f8 - refactor: 为所有纯函数添加 @__NO_SIDE_EFFECTS__ 注释 (#4907)
0a9ed - feat!: 放弃对 Vue 2 的支持,优化打包并清理 (#4349)

根据 MIT 许可证发布。