Augustin Riedinger
Augustin Riedinger

Reputation: 22238

nuxt component : computed vs data

In my nuxt component, I can't understand the difference between computed and data. I get the difference between data and asyncData but there is nothing regarding those two attributes.

<template>
  {{computedMessage}}
  {{dataMessage}}
</template>
<script>
  export default {
    computed: {
      computedMessage(){
        return this.$store.state.whatever;
      }
    },
    data() {
      return {
        dataMessage: "Hi there"
      }
    }
  }
</script>

Upvotes: 3

Views: 5539

Answers (2)

HMilbradt
HMilbradt

Reputation: 4639

The difference between computed and data is not reactivity. Both are fully reactive, as seen here. The real difference between the two is essentially this:

They both serve very different purposes, but together give you some powerful tools for data manipulation.

For example:

export default {
  mounted() {
    console.log(this.adults)
  }
  data() {
    return {
      users: [
        { name: 'Jack', age: 12 },
        { name: 'Jill', age: 53 },
        { name: 'Smith', age: 29 },
        { name: 'Matt', age: 18 }
      ]
    }
  },
  computed: {
    adults() {
      return this.users.filter(user => user.age >= 18)
    }
  }
}

This example will return 3 users from this.adults: Jill, Smith, and Matt. Without a computed property, you'd need to call a method to compute this, and you'd need to re-call it every single time you need to access that data again.

What's great about using computed properties is that their results are cached, similar to Vuex getters. This can obviously have some huge benefits when working with larger data sets.

So in summary, data is used for storing data, and computed is used for calculating new results based on data without needing to change the original state.

So now to your points:

If data is 100% static, then why make it a function?

This is because Vue shares references to all its properties, including data, between instances of the same component. So instead of declaring a plain data object, we declare a function that returns a fresh version each time it's instantiated.

If I want to have process.env in the function, should it be in computed or in data?

You're able to access process.env in either computed or data. In general, if you have access to the Nuxt instance using this, then chances are you also have access to the process.env properties.

Upvotes: 5

Hias
Hias

Reputation: 57

Well the difference between data and computed is that computed is reactive and data is static. So if you want to use data that gets automatically updated, you have to use computed.

computedis for example often used when you have to wait for data (e.g. from REST api), but you don't want to block your UI. So you assign a computedvariable and the part of your UI is updated when the data has arrived.

To understand, why data needs to be a function, you should have a look at this.

Upvotes: -2

Related Questions