Telegram Group & Telegram Channel
Глубокое клонирование реактивных объектов в Vue 3

Vue 3 использует Proxy для реактивности, что создает проблемы при попытке клонировать объекты. Стандартные методы работают не так, как ожидается:

const state = reactive({ user: { name: "Al" } });

// Проблемы:
const badCopy1 = { ...state }; // сохраняет Proxy-ссылки
const badCopy2 = JSON.parse(JSON.stringify(state)); // теряет методы и Proxy


3 рабочих способа

1. Комбинация toRaw + structuredClone

import { toRaw } from 'vue';

const original = reactive({ data: 123 });
const copy = structuredClone(toRaw(original));


2. Ручное глубокое копирование

function deepClone(obj) {
if (obj === null || typeof obj !== 'object') return obj;
const clone = Array.isArray(obj) ? [] : {};
for (const key in obj) {
clone[key] = deepClone(obj[key]);
}
return clone;
}

const copy = reactive(deepClone(toRaw(original)));


3. Библиотечные решения

import { cloneDeep } from 'lodash-es';
const copy = reactive(cloneDeep(toRaw(obj)));


#tip #reactivity



tg-me.com/vuefaq/1187
Create:
Last Update:

Глубокое клонирование реактивных объектов в Vue 3

Vue 3 использует Proxy для реактивности, что создает проблемы при попытке клонировать объекты. Стандартные методы работают не так, как ожидается:

const state = reactive({ user: { name: "Al" } });

// Проблемы:
const badCopy1 = { ...state }; // сохраняет Proxy-ссылки
const badCopy2 = JSON.parse(JSON.stringify(state)); // теряет методы и Proxy


3 рабочих способа

1. Комбинация toRaw + structuredClone

import { toRaw } from 'vue';

const original = reactive({ data: 123 });
const copy = structuredClone(toRaw(original));


2. Ручное глубокое копирование

function deepClone(obj) {
if (obj === null || typeof obj !== 'object') return obj;
const clone = Array.isArray(obj) ? [] : {};
for (const key in obj) {
clone[key] = deepClone(obj[key]);
}
return clone;
}

const copy = reactive(deepClone(toRaw(original)));


3. Библиотечные решения

import { cloneDeep } from 'lodash-es';
const copy = reactive(cloneDeep(toRaw(obj)));


#tip #reactivity

BY Vue-FAQ




Share with your friend now:
tg-me.com/vuefaq/1187

View MORE
Open in Telegram


Vue FAQ Telegram | DID YOU KNOW?

Date: |

Start with a fresh view of investing strategy. The combination of risks and fads this quarter looks to be topping. That means the future is ready to move in.Likely, there will not be a wholesale shift. Company actions will aim to benefit from economic growth, inflationary pressures and a return of market-determined interest rates. In turn, all of that should drive the stock market and investment returns higher.

How Does Telegram Make Money?

Telegram is a free app and runs on donations. According to a blog on the telegram: We believe in fast and secure messaging that is also 100% free. Pavel Durov, who shares our vision, supplied Telegram with a generous donation, so we have quite enough money for the time being. If Telegram runs out, we will introduce non-essential paid options to support the infrastructure and finance developer salaries. But making profits will never be an end-goal for Telegram.

Vue FAQ from cn


Telegram Vue-FAQ
FROM USA