Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

304
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda