Skip to content

useCloned

Category
Export Size
289 B
Last Changed
8 minutes ago

Reactive clone of a ref. By default, it use JSON.parse(JSON.stringify()) to do the clone.

Demo

Usage

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'

Changes to the source are not reflected in the cloned ref immediately. Use { flush: 'sync' } to obtain the updated value without delay.

ts
const { 
cloned
} = useCloned(original, {
flush
: 'sync' })
original.value.key = 'some new value'
console
.
log
(
cloned
.value.key) // 'some new value'
js
'use strict'
const { cloned } = useCloned(original, { flush: 'sync' })
original.value.key = 'some new value'
console.log(cloned.value.key) // 'some new value'

Manual cloning

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'

Custom Clone Function

Using klona for example:

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

Type Declarations

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
<
T
>,
):
UseClonedReturn
<
T
>

Source

SourceDemoDocs

Contributors

Anthony Fu
Anthony Fu
Lazizbek Ergashev
Robin
iXueJie
IlyaL
James Garbutt
青椒肉丝
ge Datou
Heartz66
Jeff Yang (楊德誠)
Akkapon Chainarong
Eduardo Wesley
Mikhailov Nikita

Changelog

Pending for release...
c5a08 - fix: make custom clone function type-safe (#5559)
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)

Released under the MIT License.