Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is difference between 'data:' and 'data()' in Vue.js?

I have used data option in two ways. In first snippet data object contains a key value, however, in second data is a function. Is there any benefits of individuals.Not able to find relevant explanations on Vue.js Docs Here are two code snippets:

new Vue({   el: "#app",   data: {       message: 'hello mr. magoo'     }  });  new Vue({   el: "#app",   data() {     return {       message: 'hello mr. magoo'     }   } }); 

Both are giving me the same output.

like image 280
Vivek Avatar asked Jan 09 '18 20:01

Vivek


People also ask

What does data () do in Vue?

data # A function that returns the initial reactive state for the component instance. The function is expected to return a plain JavaScript object, which will be made reactive by Vue.

What is the difference between props and data Vue?

So what's the difference between props and data? Data is the private memory of each component where you can store any variables you need. Props are how you pass this data from a parent component down to a child component.

What does $t mean in Vue?

Vuex is a state management pattern for vue. js. $t is the injected method from vue. js or Vue. i18n.

Can I use props in data Vue?

Using props in VueAfter you have set up the props, you can then use it inside your component as though the data was defined inside the same component.


1 Answers

It seems as though the comments on your question missed a key point when considering your specific code example.

In a root Vue instance i.e. constructed via new Vue({ ... }), you can simply use data: { ... } without any problems. The issue is when you have reusable components that are defined via Vue.component(...). In these instances, you need to either use data() {return { ... };} or data: function() {return { ... };}.

The reason for this is to ensure that for each individual instance of the reusable child component, there is a unique object containing all of the data being operated on. If, in a child component, you instead use data: { ... }, that same data object will be shared between the child components which can cause some nasty bugs.

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

like image 139
B. Fleming Avatar answered Oct 05 '22 02:10

B. Fleming