Vue3 Ref重新赋值导致地址指向改变问题

为了确保 ref 中 list 内部的对象引用地址也保持不变,可以递归地更新每个子对象,而不是删除和重新创建对象。这样可以确保所有嵌套的对象引用都保持不变。

import { ref } from 'vue';

const test = ref({
    list: [
        {            
            name: "1719224770324",
            timeStamp: 1719224765841,
            id: "4edcce29-f7c3-4e4c-a865-323151290376",
            customRules: []
        }
    ],
    form: {},
    config: {
        colon: false,

    }
});

// 深拷贝函数
const deepClone = (obj) => {
    if (obj === null || typeof obj !== 'object') {
        return obj;
    }

    if (Array.isArray(obj)) {
        return obj.map(item => deepClone(item));
    }

    const clonedObj = {};
    for (const key in obj) {
        if (obj.hasOwnProperty(key)) {
            clonedObj[key] = deepClone(obj[key]);
        }
    }
    return clonedObj;
};

// 更新对象内容而不改变其引用的递归函数
const updateObject = (target, source) => {
    for (const key in source) {
        if (source.hasOwnProperty(key)) {
            if (typeof source[key] === 'object' && source[key] !== null) {
                if (!target[key]) {
                    target[key] = Array.isArray(source[key]) ? [] : {};
                }
                updateObject(target[key], source[key]);
            } else {
                target[key] = source[key];
            }
        }
    }
};

// 将对象深拷贝并更新
const newTestValue = deepClone(test.value);
newTestValue.list[0].control.value = "新值";  // 修改属性以示例

updateObject(test.value, newTestValue);

console.log(test.value);  // 输出更新后的对象


在这个示例中:
1. deepClone 函数递归地深拷贝一个对象。
2. updateObject 函数递归地更新目标对象 target 的每个属性,使其匹配源对象 source 的属性,而不会改变对象的引用。

这样,test.value 及其内部的对象引用都将保持不变,而对象内容则会被更新。

Lyndon
Lyndon

对世界的各种充满着好奇, 探索一切未知.

文章: 37

留下评论

您的邮箱地址不会被公开。 必填项已用 * 标注