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

444
Vistas
Why is empty object in Vue3 not reactive?

When I create a ref from an empty object and later add object properties, there is no reactivity:

<template>
  <p>{{hello}}</p>
  <button @click="add()">Click me</button>
</template>

<script>
import {ref} from 'vue';
export default {
  name: "Test",
  setup(){
    const myData = ref({});
    return {myData}
  },
  methods: {
    add(){
      this.myData["text"] = "Hello";
      console.log(this.myData);
    }
  },
  computed: {
    hello(){
      if(this.myData.hasOwnProperty("text")) return this.myData["text"];
      return "no text";
    }
  }
}
</script>

Clicking the button shows that myData has changed but the computed property hello does not update.

Also tried reactive({}) instead of ref({}) without success.

What works is this const myData = ref({"text": "no text"});. But why does the empty object not work?

over 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

Try to you update your ref object like

this.myData = {"text": "Hello"}

const { ref, computed } = Vue
const app = Vue.createApp({
  /*setup(){
    const myData = ref({});
    const hello = computed(() => myData.value.hasOwnProperty("text") ? myData.value.text : myData.value = "no text")
    const add = () => {
      if(Object.keys(myData.value).length === 0) {
        myData.value = {'text': "Hello"};
      } else {
        myData.value.otherProperty = "Hello again"
      }
    }
    return { myData, add, hello }
  },*/
  setup(){
    const myData = ref({});
    return { myData }
  },
  methods: {
    add(){
      if(Object.keys(this.myData).length === 0) {
        this.myData = {"text": "Hello"}
      } else {
        this.myData.otherProperty = "Hello again"
      }
      console.log(this.myData)
    },
  },
  computed: {
    hello(){
      return Object.keys(this.myData).length !== 0 ? this.myData[Object.keys(this.myData)[Object.keys(this.myData).length - 1]] : "no text"
    }
  }
})
app.mount('#demo')
<script src="https://unpkg.com/vue@3.2.29/dist/vue.global.prod.js"></script>
<div id="demo">
  <p>{{ hello }}</p>
  <button @click="add">Click me 2 times</button>
</div>

over 4 years ago · Santiago Trujillo Denunciar

0

If you change your computed property to be defined such that it references myData['text'] directly before returning, things work as expected:

  computed: {
    hello() {
      return this.myData['text'] || 'no text'; // works
    }

I suspect what's going on with your original code is that the Vue dependency-tracking code is not able to see that your function depends on myData. Consider that hello is being called (by Vue) before the text property exists on the object. In that case, the function returns before actually touching the proxied value (it short-circuits as soon as it sees that hasOwnProperty has returned false).

Dependency tracking in Vue is done dynamically, so if your computed property doesn't touch any reactive variables when called, Vue doesn't see it as having any external dependencies, and so won't bother calling it in the future. It will just use the previously-cached value for subsequent calls.

over 4 years ago · Santiago Trujillo 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