SoFunction
Updated on 2025-04-04

Deep cloning method of vue object

Deep cloning of vue objects

Method 1

Through js serialization, convert js into strings, and then convert strings into js objects

var olbObj = {a:1};
var str = (obj); //Serialize the objectvar newobj = (str); //reduction//Equivalent tovar newObj = ((olbObj ))

Method 2

ES6 syntax object expansion operator performs object expansion assignment

var a = {a:0}
var b = {...a}

Method 3

Perform traversal copying of objects and copying each property of the object, so that the object can be deeply cloned

function newobj(obj) {
  var str, newobj =  === Array ? [] : {};
  //The constructor property returns a reference to the array function that created this object.  Create empty data of the same type  if (typeof obj !== 'object') {
    return;
  } else {
    for (var i in obj) {
      if (typeof obj[i] === 'object'){//Judge whether this property of the object is an object        newobj[i] = newObj(obj[i]);//If the object is called in a nested manner      }else{
        newobj[i] = obj[i];
      }
    }
  }
  return newobj;//Return the object after deep cloning}

Problems encountered when cloning objects with vue

We know that when we need to deeply clone an object or array, change the data obtained, and the original data remains unchanged. The simpler functions used are basically all

let b = ((a))

But if we cloned a vue responsive object, we found that using this method was useless

So I need a tool function old deep cloning

//Deep cloningexport const deepClone = (source) => {
  var sourceCopy = source instanceof Array ? [] : {}
  for (var item in source) {
    sourceCopy[item] = typeof source[item] === 'object' ? deepClone(source[item]) : source[item]
  }
  return sourceCopy
}
let b = deepClone (a)

This will result in a responsive

The above is personal experience. I hope you can give you a reference and I hope you can support me more.