跳到主要内容

toRefs

分类
导出大小
285 B
上次更改
7 个月前

扩展了 toRefs,它也接受一个对象的 refs。

用法

ts
import { 
toRefs
} from '@vueuse/core'
import {
reactive
,
ref
} from 'vue'
const
objRef
=
ref
({
a
: 'a',
b
: 0 })
const
arrRef
=
ref
(['a', 0])
const {
a
,
b
} =
toRefs
(
objRef
)
const [
a
,
b
] =
toRefs
(
arrRef
)
const
obj
=
reactive
({
a
: 'a',
b
: 0 })
const
arr
=
reactive
(['a', 0])
const {
a
,
b
} =
toRefs
(
obj
)
const [
a
,
b
] =
toRefs
(
arr
)

用例

解构一个 props 对象

vue
<script lang="ts">
import { 
toRefs
,
useVModel
} from '@vueuse/core'
export default {
setup
(
props
) {
const
refs
=
toRefs
(
useVModel
(
props
, 'data'))
console
.
log
(
refs
.a.value) // props.data.a
refs
.a.value = 'a' // emit('update:data', { ...props.data, a: 'a' })
return { ...
refs
}
} } </script> <template> <
div
>
<
input
v-model
="a"
type
="text">
<
input
v-model
="b"
type
="text">
</
div
>
</template>

类型声明

ts
export interface ToRefsOptions {
  /**
   * Replace the original ref with a copy on property update.
   *
   * @default true
   */
  
replaceRef
?:
MaybeRefOrGetter
<boolean>
} /** * Extended `toRefs` that also accepts refs of an object. * * @see https://vueuse.org.cn/toRefs * @param objectRef A ref or normal object or array. * @param options Options */ export declare function
toRefs
<
T
extends object>(
objectRef
:
MaybeRef
<
T
>,
options
?: ToRefsOptions,
):
ToRefs
<
T
>

来源

源码文档

贡献者

Anthony Fu
Anthony Fu
丶远方
Robin
IlyaL
Aaron-zon
Kasper Seweryn
ByMykel
vaakian X
chaii3
webfansplz
William T. Kirby

更新日志

v13.1.0
c1d6e - feat(shared): 确保返回类型存在 (#4659)
v12.8.0
7432f - feat(types): 废弃 MaybeRefMaybeRefOrGetter,转而使用 Vue 的原生类型 (#4636)
v12.3.0
59f75 - feat(toValue): 废弃 @vueuse/shared 中的 toValue,转而使用 Vue 的原生函数
0a9ed - feat!: 放弃对 Vue 2 的支持,优化打包并清理 (#4349)
v10.3.0
5309c - 修复:不触发不必要的 watchEffects (#3260)
v10.2.1
9f998 - 修复:修复由递归 setPrototypeOf 导致的堆栈溢出 (#3166)

根据 MIT 许可证发布。