IT이야기

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

cyworld 2022. 4. 25. 22:02
반응형

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

그리고 ES6 지방 화살표 (=>)는 내가 일반적으로 사용한 것이다.

data:()=>({
  obj
})

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

네가 기대한 대로 되지 않을 거야.this.stuffProp을 얻지 못하다stuffProp프로펠러의 가치(이유는 아래 참조).

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

화살표 기능 사용 안 함(() => {}Vue 메서드를 선언할 때.그들은 그 집을 집어들었다.this현재의 범위로부터(일반적으로)window(), Vue 인스턴스를 반영하지 않는다.

From the API Docs:

특성(예: 화살표 기능)과 함께 사용하면 안 된다는 점에 유의하십시오.data: () => { return { a: this.myProp }}그 이유는 화살표 함수가 상위 컨텍스트를 바인딩하기 때문이다.this당신이 기대한 대로 Vue 인스턴스가 되지 않을 것이다.this.myProp정의되지 않을 것이다.

ES5 또는 ES6 구문과 관련이 있으며, 화살표 기능을 사용한 경우()=>이전 스크립트에서는 다음 코드를 사용하는 것이 안전하다.

// tested and this.myData can be accessed in the component
data: () => { return {
    myData: 'someData',
    myStuff: this.stuffProp
} }

// this also works
data: () => ({
    myData: 'someData',
    myStuff: this.stuffProp
})

ReferenceURL : https://stackoverflow.com/questions/48980865/vue-js-difference-of-data-return-vs-data

반응형