在 Vue 3 中,當子組件需要修改父組件傳遞的數據副本并同步更新時,可以通過以下步驟實現:
方法 1:使用?v-model
?和計算屬性(實時同步)
父組件:
vue
<template><ChildComponent v-model="parentData" /> </template><script setup> import { ref } from 'vue'; const parentData = ref(initialValue); </script>
子組件:
vue
<template><input v-model="modelValueComputed" /> </template><script setup> import { computed } from 'vue';const props = defineProps(['modelValue']); const emit = defineEmits(['update:modelValue']);// 計算屬性實現雙向綁定 const modelValueComputed = computed({get: () => props.modelValue,set: (value) => emit('update:modelValue', value) }); </script>
方法 2:使用副本和偵聽器(實時同步)
父組件同上。
子組件:
vue
<template><input v-model="localData" /> </template><script setup> import { ref, watch } from 'vue';const props = defineProps(['modelValue']); const emit = defineEmits(['update:modelValue']);// 創建副本 const localData = ref(props.modelValue);// 監聽本地副本變化,同步到父組件 watch(localData, (newVal) => {emit('update:modelValue', newVal); });// 監聽父組件數據變化,更新副本 watch(() => props.modelValue, (newVal) => {localData.value = newVal; }); </script>
方法 3:手動觸發更新(如提交按鈕)
父組件:
vue
<template><ChildComponent :data="parentData" @update="handleUpdate" /> </template><script setup> import { ref } from 'vue'; const parentData = ref(initialValue);const handleUpdate = (newVal) => {parentData.value = newVal; }; </script>
子組件:
vue
<template><input v-model="localData" /><button @click="submit">提交</button> </template><script setup> import { ref, watch } from 'vue';const props = defineProps(['data']); const emit = defineEmits(['update']);// 初始化副本 const localData = ref(props.data);// 父組件數據變化時更新副本 watch(() => props.data, (newVal) => {localData.value = newVal; });const submit = () => {emit('update', localData.value); }; </script>
關鍵點說明:
-
副本創建:子組件通過?
ref
?或?reactive
?創建數據的副本,避免直接修改 Props。 -
數據同步:
-
實時同步:通過?
watch
?監聽副本變化并觸發事件 (emit
),同時監聽 Props 更新副本。 -
手動同步:在用戶操作(如點擊按鈕)時提交修改。
-
-
雙向綁定:利用?
v-model
?語法糖簡化父子通信,自動處理 Prop 和事件。 -
更新策略:根據場景選擇是否實時同步或手動同步,避免循環更新或數據不一致。
注意事項:
-
深拷貝:如果傳遞的是對象/數組,需使用深拷貝(如?
JSON.parse(JSON.stringify(props.data))
)避免引用問題。 -
性能:頻繁的?
watch
?可能影響性能,復雜場景可考慮防抖或優化監聽邏輯。 -
數據一致性:父組件更新后,若需子組件副本同步,務必監聽 Prop 變化并更新副本。