跳到主要内容

useCloned

分类
导出大小
289 B
上次更改
8 个月前

一个 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 {
/** * Custom clone function. * * By default, it use `JSON.parse(JSON.stringify(value))` to clone. */
clone
?: (
source
:
T
) =>
T
/** * Manually sync the ref * * @default false */
manual
?: boolean
} export interface
UseClonedReturn
<
T
> {
/** * Cloned ref */
cloned
:
Ref
<
T
>
/** * Ref indicates whether the cloned data is modified */
isModified
:
Ref
<boolean>
/** * Sync cloned data with source manually */
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

更新日志

v12.8.0
7432f - feat(types): 废弃 MaybeRefMaybeRefOrGetter,转而使用 Vue 的原生类型 (#4636)
v12.4.0
6018c - feat: 返回 isModified (#4470)
v12.3.0
59f75 - feat(toValue): 废弃 @vueuse/shared 中的 toValue,转而使用 Vue 的原生函数
0a9ed - feat!: 放弃对 Vue 2 的支持,优化打包并清理 (#4349)
v10.8.0
e262f - fix: 修正返回类型 (#3711)
v10.2.0
6d630 - fix: 检查 getter 函数以进行监听 (#3142)

根据 MIT 许可证发布。