Home > Enterprise >  VueJS - create readonly copy of a ref object (Composition API)
VueJS - create readonly copy of a ref object (Composition API)

Time:03-08

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?

CodePudding user response:

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)

CodePudding user response:

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

  • Related