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
'IT이야기' 카테고리의 다른 글
Vue 2 + 요소 UI + Laravel 5.3 스타터 (0) | 2022.04.25 |
---|---|
아폴로는 왜 첫 번째 요청으로 데이터를 얻을 수 없는가? (0) | 2022.04.25 |
리눅스 커널에 있는 함수의 포인터에서 함수의 이름을 가져오는 방법? (0) | 2022.04.25 |
여러 파일을 base64 문자열로 변환하는 방법? (0) | 2022.04.25 |
v-model에 소품 바인딩 시도 중 (0) | 2022.04.25 |