Skip to content

useCloned

类别
导出体积
499 B
上次更改
2 minutes 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, sync } = useCloned(original, { clone: klona })

类型声明

typescript
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>
  /**
   * 手动将克隆的数据与源同步
   */
  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
ge Datou
Heartz66
Jeff Yang (楊德誠)
Akkapon Chainarong
Eduardo Wesley
Mikhailov Nikita

更新日志

v10.8.0 on 2/20/2024
e262f - fix: correct return type (#3711)
v10.2.0 on 6/16/2023
6d630 - fix: check for getter function to watch (#3142)
v10.0.0-beta.4 on 4/13/2023
4d757 - feat(types)!: rename MaybeComputedRef to MaybeRefOrGetter
v9.2.0 on 9/5/2022
369e1 - feat(useVModel): support clone option (#2022)
0a0a1 - feat: new function (#2045)