Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue JS: Difference of data() { return {} } vs data:() => ({ })

I'm curious both of this data function, is there any difference between this two.

I usually saw is

data () {   return {     obj   } } 

And ES6 fat arrow (=>) which I typically used

data:()=>({   obj }) 
like image 741
BGTabulation BGTabulate Avatar asked Feb 26 '18 03:02

BGTabulation BGTabulate


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 difference between props and data in 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.

Can you use arrow functions in Vue?

While you should not use arrow functions to define methods, it's fine to use them inside your methods as the this keyword will bind to the correct parent reference. const app = Vue.

How is Vue different from JavaScript?

js is a cross-platform and open-source back-end framework that executes JavaScript code on the server-side. Vue. js is a structural, open-source JavaScript framework that is used for building UIs and single-page applications.


1 Answers

No difference in your specific example, but there is a very important difference between those two notations, specially when it comes to Vue.js: the this won't reflect the vue instance in arrow functions.

So if you ever have something like:

export default {     props: ['stuffProp'],     data: () => ({       myData: 'someData',       myStuff: this.stuffProp     }) } 

It won't work as you expect. The this.stuffProp won't get the stuffProp prop's value (see below for more on the reason why).

Fix

Change the arrow function to, either (ES6/EcmaScript 2015 notation):

export default {     props: ['stuffProp'],     data() {                                   // <== changed this line       return {         myData: 'someData',         myStuff: this.stuffProp       }     } } 

Or to (regular, ES5 and before, notation):

export default {     props: ['stuffProp'],     data: function() {                           // <== changed this line      return {         myData: 'someData',         myStuff: this.stuffProp       }     } } 

Reason

Don't use arrow functions (() => {}) when declaring Vue methods. They pick up the this from the current scope (possibly window), and will not reflect the Vue instance.

From the API Docs:

Note that you should not use an arrow function with the data property (e.g. data: () => { return { a: this.myProp }}). The reason is arrow functions bind the parent context, so this will not be the Vue instance as you expect and this.myProp will be undefined.

like image 111
acdcjunior Avatar answered Oct 06 '22 16:10

acdcjunior