You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue组合式API中克隆Props实现本地修改不影响父组件

解决Vue组件中Props深克隆问题

你的核心问题是浅克隆无法切断嵌套对象的引用,导致修改组件内的form时同步修改了父组件的record。以下是几种可靠的深克隆方案:

方案1:JSON序列化(简单通用,无特殊类型时首选)

适合对象中只包含基本类型、普通对象、数组的场景,缺点是会丢失Date、函数、Symbol等特殊类型的数据。

修改你的watchEffect代码:

watchEffect(() => {
  form.value = JSON.parse(JSON.stringify(props.record))
})

方案2:使用structuredClone(现代浏览器支持,处理更多类型)

浏览器原生API,支持克隆Date、Map、Set、数组、对象等大部分类型,兼容性较好(除了IE)。

watchEffect(() => {
  form.value = structuredClone(props.record)
})

方案3:手动递归克隆(自定义处理特殊类型)

如果你的record包含需要特殊处理的类型(比如自定义类实例),可以手动实现递归克隆:

function deepClone(obj) {
  // 处理非对象类型
  if (obj === null || typeof obj !== 'object') return obj
  // 处理Date
  if (obj instanceof Date) return new Date(obj.getTime())
  // 处理数组
  if (obj instanceof Array) return obj.map(item => deepClone(item))
  // 处理普通对象
  const clonedObj = {}
  for (const key in obj) {
    if (obj.hasOwnProperty(key)) {
      clonedObj[key] = deepClone(obj[key])
    }
  }
  return clonedObj
}

// 在setup中使用
watchEffect(() => {
  form.value = deepClone(props.record)
})

完整修正后的组件代码

<template>
  <input-text v-model="form.name" />
</template>

<script>
import { defineComponent, ref, watchEffect } from 'vue'

export default defineComponent({
  props: {
    record: {
      type: Object,
      required: true,
      default: () => ({}),
    },
  },
  setup(props) {
    const form = ref({})

    watchEffect(() => {
      // 这里替换成你选择的深克隆方式
      form.value = JSON.parse(JSON.stringify(props.record))
    })

    return { form }
  },
})
</script>

注意:你原代码中的dForm.value是笔误,应该改为form.value。

内容的提问来源于stack exchange,提问作者George Morris

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 10:20:13