Skip to content

useCloned

类别
导出体积
289 B
上次更改
7 months ago

对 ref 进行响应式克隆。默认情况下,它使用 JSON.parse(JSON.stringify()) 进行克隆。

示例

使用方法

ts
import { 
useCloned
} from '@vueuse/core'
const
original
=
ref
({
key
: 'value' })
const {
cloned
} =
useCloned
(
original
)
original
.
value
.
key
= 'some new value'
console
.
log
(
cloned
.
value
.
key
) // 'value'

手动克隆

ts
import { 
useCloned
} from '@vueuse/core'
const
original
=
ref
({
key
: 'value' })
const {
cloned
,
sync
} =
useCloned
(
original
, {
manual
: true })
original
.
value
.
key
= 'manual'
console
.
log
(
cloned
.
value
.
key
) // 'value'
sync
()
console
.
log
(
cloned
.
value
.
key
)// 'manual'

自定义克隆函数

例如使用 klona

ts
import { 
useCloned
} from '@vueuse/core'
import {
klona
} from 'klona'
const
original
=
ref
({
key
: 'value' })
const {
cloned
,
isModified
,
sync
} =
useCloned
(
original
, {
clone
:
klona
})

类型声明

ts
export interface 
UseClonedOptions
<
T
= any> extends WatchOptions {
/** * 自定义克隆函数。 * * 默认情况下,它使用 `JSON.parse(JSON.stringify(value))` 进行克隆。 */
clone
?: (
source
:
T
) =>
T
/** * 手动同步 ref * * @default false */
manual
?: boolean
} export interface
UseClonedReturn
<
T
> {
/** * 克隆的 ref */
cloned
:
Ref
<
T
>
/** * Ref表示克隆的数据是否被修改。 */
isModified
:
Ref
<boolean>
/** * 手动将克隆的数据与源同步 */
sync
: () => void
} export type
CloneFn
<
F
,
T
=
F
> = (
x
:
F
) =>
T
export declare function
cloneFnJSON
<
T
>(
source
:
T
):
T
export declare function
useCloned
<
T
>(
source
:
MaybeRefOrGetter
<
T
>,
options
?:
UseClonedOptions
,
):
UseClonedReturn
<
T
>

源码

源码演示文档

贡献者

一纸忘忧
Anthony Fu
Anthony Fu
IlyaL
James Garbutt
青椒肉丝
ge Datou
Heartz66
Jeff Yang (楊德誠)
Akkapon Chainarong
Eduardo Wesley
Mikhailov Nikita

更新日志

7432f - feat(types): deprecate MaybeRef and MaybeRefOrGetter in favor of Vue's native (#4636)
6018c - feat: return isModified (#4470)
59f75 - feat(toValue): deprecate toValue from @vueuse/shared in favor of Vue's native
0a9ed - feat!: drop Vue 2 support, optimize bundles and clean up (#4349)
e262f - fix: correct return type (#3711)
6d630 - fix: check for getter function to watch (#3142)