Skip to content

useCloned

Category
Export Size
499 B
Last Changed
15 minutes ago

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

Demo

使用方法

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>

Source

SourceDemoDocs

贡献者

丶远方
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

Released under the MIT License.