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

305
Vistas
What is the difference between declaring variables in data or setup function?

I am new to Vue and as I see it, both functions can be used to define/initialize variables used in the file. But from what I read it is not clear to me what the differences are and when I should use which one to declare/initialize variables.

So far I've only realized that variables declared in the data function are then wrapped in a proxy object, which causes troubles when I try to save the object in a database. Now I'm thinking whether I should keep using the data function and create a normal object from the proxy when I need to save it, or whether I should instead just use the setup function.

In case it's not clear what I'm talking about:

Example A:

data() {
  return {
    person: {
      age: 5,
      name: "Peter"
    }
  }
}

Example B:

setup() {
  return {
    person: {
      age: 5,
      name: "Peter"
    }
  }
}
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

You can think of Example A as:

setup() {
  const person = reactive({
    age: 5,
    name: "Peter"
  })
  return {
    person
  }
}

But in Example B, object person didn't wrapped by reactive, so it won't be watched or reactive.

A more proper example for data -> setup:

import { reactive, toRefs } from 'vue'

setup() {
  const data = reactive({
    person: {
      age: 5,
      name: "Peter"
    }
  })
  return {
    '$data': data,
    ...toRefs(data), // so that `person` can be used in <template />
  }
}
about 4 years ago · Juan Pablo Isaza Denunciar

0

The difference is that data() is the sintaxis used in the options api of vue(the typical approach in Vue 2 which is also valid in Vue 3) and the setup() sintaxis is part of the composition api(introduced in vue 3). This composition Api makes the javascript block of a vue component more uniform and reusable(among other advantages). https://fjolt.com/article/vue-composition-api-vs-options-api#:~:text=What%20is%20the%20difference%20between,like%20in%20the%20Options%20API.

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