TestUser_wlxvg
TestUser_wlxvg

Reputation: 33

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

I am new to Vue.js 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"
    }
  }
}

Upvotes: 2

Views: 1239

Answers (2)

The difference is that data() is the syntax used in the options API of Vue.js (the typical approach in Vue.js 2 which is also valid in Vue.js 3) and the setup() sintaxis is part of the composition API (introduced in Vue.js 3). This composition API makes the JavaScript block of a Vue.js 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.

Upvotes: 1

AmberWagner
AmberWagner

Reputation: 126

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 />
  }
}

Upvotes: 1

Related Questions