跳到主要内容

computedWithControl

分类
导出大小
251 B
上次更改
上个月
别名
controlledComputed
相关

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

用法

ts
import { 
computedWithControl
} from '@vueuse/core'
const
source
=
ref
('foo')
const
counter
=
ref
(0)
const
computedRef
=
computedWithControl
(
() =>
source
.
value
, // watch source, same as `watch`
() =>
counter
.
value
, // computed getter, same as `computed`
)
js
import { computedWithControl } from '@vueuse/core'
const source = ref('foo')
const counter = ref(0)
const computedRef = computedWithControl(
  () => source.value, // watch source, same as `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 {
  /**
   * Force update the computed value.
   */
  
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!: 弃用别名导出,转而使用原始函数名称 (#5009)
v13.4.0
ffc1a - fix: 允许深度监听源 (#4786)
v13.1.0
c1d6e - feat(shared): 确保返回类型存在 (#4659)
0a9ed - feat!: 放弃对 Vue 2 的支持,优化打包并清理 (#4349)
5725a - fix: 允许 computedWithControl getter 中可选的 oldValue 参数 (#4132)
v10.8.0
a086e - fix: 更严格的类型

根据 MIT 许可证发布。