Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

288
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda