Home > Software engineering >  What is the difference between declaring variables in data or setup function?
What is the difference between declaring variables in data or setup function?

Time:06-06

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

CodePudding user response:

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

CodePudding user response:

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 is the difference between,like in the Options API.

  • Related