Skip to content

computedWithControl

类别
导出体积
251 B
上次更改
3 days ago
别名
controlledComputed
相关

显式定义计算属性的依赖关系。

用法

ts
import { 
computedWithControl
} from '@vueuse/core'
const
source
=
ref
('foo')
const
counter
=
ref
(0)
const
computedRef
=
computedWithControl
(
() =>
source
.
value
, // 监视 source,与 `watch` 相同
() =>
counter
.
value
, // 计算属性的 getter,与 `computed` 相同
)
js
import { computedWithControl } from '@vueuse/core'
const source = ref('foo')
const counter = ref(0)
const computedRef = computedWithControl(
  () => source.value, // 监视 source,与 `watch` 相同
  () => counter.value,
)

通过这种方式,counter 的更改不会触发 computedRef 更新,但是 source ref 会。

ts
console
.
log
(
computedRef
.
value
) // 0
counter
.
value
+= 1
console
.
log
(
computedRef
.
value
) // 0
source
.
value
= 'bar'
console
.
log
(
computedRef
.
value
) // 1

手动触发

你还可以通过以下方式手动触发计算属性的更新:

ts
const 
computedRef
=
computedWithControl
(
() =>
source
.
value
,
() =>
counter
.
value
,
)
computedRef
.
trigger
()

深度观察

computed 不同,computedWithControl 默认是浅层的。

您可以指定与 watch 相同的选项来控制行为:

ts
const 
source
=
ref
({
name
: 'foo' })
const
computedRef
= computedWithControl(
source
,
() => counter.value, {
deep
: true },
)

类型声明

ts
export interface ComputedWithControlRefExtra {
  /**
   * 强制更新计算值
   */
  
trigger
: () => void
} export interface
ComputedRefWithControl
<
T
>
extends
ComputedRef
<
T
>,
ComputedWithControlRefExtra {} export interface
WritableComputedRefWithControl
<
T
>
extends
WritableComputedRef
<
T
>,
ComputedWithControlRefExtra {} export type
ComputedWithControlRef
<
T
= any> =
|
ComputedRefWithControl
<
T
>
|
WritableComputedRefWithControl
<
T
>
export declare function
computedWithControl
<
T
,
S
>(
source
:
WatchSource
<
S
> |
WatchSource
<
S
>[],
fn
:
ComputedGetter
<
T
>,
options
?:
WatchOptions
,
):
ComputedRefWithControl
<
T
>
export declare function
computedWithControl
<
T
,
S
>(
source
:
WatchSource
<
S
> |
WatchSource
<
S
>[],
fn
:
WritableComputedOptions
<
T
>,
options
?:
WatchOptions
,
):
WritableComputedRefWithControl
<
T
>
/** @deprecated use `computedWithControl` instead */ export declare const
controlledComputed
: typeof
computedWithControl

源码

源码文档

贡献者

Anthony Fu
一纸忘忧
Anthony Fu
Vida Xie
SerKo
Ronnie Dutta
broBinChen
Robin
Yun Hao
sun0day
kongmoumou

更新日志

e5f74 - feat!: deprecate alias exports in favor of original function names (#5009)
ffc1a - fix: allow deeply watching source (#4786)
c1d6e - feat(shared): ensure return types exists (#4659)
0a9ed - feat!: drop Vue 2 support, optimize bundles and clean up (#4349)
5725a - fix: allow optional oldValue parameter in computedWithControl getter (#4132)
a086e - fix: stricter types