yoeriboven
yoeriboven

Reputation: 3571

Declaring data in Vue with components

According to the docs, this is how you declare data in Vue:

data: {
    name: 'Vue.js'
}

However, when I do that it doesn't work and an error shows in the console:

The "data" option should be a function that returns a per-instance value in component definitions.

I change it to the following and then it works fine:

data() {
    return {
        name: 'Vue.js',
    }
}

Why do the Vue docs show the top bit of code when it doesn't work? Is there something wrong on my end?

Edit: This only happens when using components.

Upvotes: 0

Views: 352

Answers (3)

yoeriboven
yoeriboven

Reputation: 3571

It turns out you need to declare data in components different than when you set it on a Vue object.

Instead, a component’s data option must be a function, so that each instance can maintain an independent copy of the returned data object:

More: Vue docs

Upvotes: 0

Sagar
Sagar

Reputation: 1335

In a root Vue instance (which is constructed via new Vue({ . . . }), you can simply use data: { . . . } without any problems.

When you are planing to reuse Vue components using Vue.component(...) or using "template" tag, Use data attribute as a function.

Please review the corresponding section of the Vue.js documentation for more information regarding this problem

https://v2.vuejs.org/v2/guide/components.html#data-Must-Be-a-Function

Upvotes: 1

Aniket G
Aniket G

Reputation: 3512

You should declare data in Vue.js by doing

var app = new Vue({
  el: '#app', //This is the container in which Vue will be in. The #app means the id of the container is app
  data: {

  }
});

Upvotes: 0

Related Questions