跳到主要內容

useCloned

類別
導出大小
262 B
上次變更
5 天前

響應式 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 })

類型宣告

typescript
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 於 2025/3/5
7432f - feat(types): 棄用 MaybeRefMaybeRefOrGetter,改用 Vue 原生型別 (#4636)
v12.4.0 於 2025/1/10
6018c - feat: 返回 isModified (#4470)
v12.3.0 於 2025/1/2
59f75 - feat(toValue): 棄用 @vueuse/sharedtoValue,改用 Vue 原生型別
v12.0.0-beta.1 於 2024/11/21
0a9ed - feat!: 移除 Vue 2 支援,最佳化 bundle 並清理 (#4349)
v10.8.0 於 2024/2/20
e262f - fix: 修正返回類型 (#3711)
v10.2.0 於 2023/6/16
6d630 - fix: 檢查要監看的 getter 函式 (#3142)
v10.0.0-beta.4 於 2023/4/13
4d757 - feat(types)!: 將 MaybeComputedRef 重新命名為 MaybeRefOrGetter

以 MIT 許可證發布。