Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

286
Views
VueJS - create readonly copy of a ref object (Composition API)

I am getting data from db by onMounted hook and showing object in a form. When user clicks to save, I just want to check if object data has changed or not.

onMounted(async () => {
  loadingBasic.value = true
  const doc = await getDocument('workspaces',props.uid) //doc is ref({}) also
  wspace.value = doc.value
  loadingBasic.value = false
})

I created a readonly object but when wspace object has changed, readonly object is changing, too. How can I create an unchanged initial copy of a ref object?

By the way, is there another easy way to check form changes?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

You are copying only the reference with wspace.value = doc.value You can copy values with:

wspace.value = {...doc.value} 

let doc1 = {a: 1, b:2}
let doc2 = {a: 1, b:2}
let wspace1 = doc1
let wspace2 = {...doc2}

wspace1.a = 3
wspace2.a = 3

console.log('wspace1 :', wspace1)
console.log('doc1 :', doc1)
console.log('wspace2 :', wspace2)
console.log('doc2 :', doc2)

about 4 years ago · Juan Pablo Isaza Report

0

Few suggestions :

  • Instead of shallow copy, you have to do deep copy of an object to maintain the initial state. You can check the difference in both here.
  • To create a deep copy of an object, You can try any of the following methods :
    • JSON.parse(JSON.stringify(object))
    • By using spread operator {...obj} and assigning the result into a new variable.
  • To quickly compare the changed and original object without any iteration. If the objects to be compared have properties in the same order, You can use JSON.stringify().

Demo :

const doc = {
    value: {
    id: 1,
    name: 'alpha'
  }
};

// making a deep copy
const deepCopy = {...doc.value}

// As user did not make any changes in the form. Comparision should return true.
console.log(JSON.stringify(deepCopy) === JSON.stringify(doc.value)); // True

// User making some changes in the form.
deepCopy.id = 2;
deepCopy.name = 'beta';

// As user make changes in the form data. Comparision should return false.
console.log(JSON.stringify(deepCopy) === JSON.stringify(doc.value)); // False

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!