본문 바로가기
Vue.js

[Vue] 화살표함수 (arrow funcion) 사용 시 주의사항 #삽질주의

by bryan.oh 2021. 1. 14.
반응형

arrow function 사용 주의 사항 
() => {}

 

결론부터

created: () => console.log(this.a)  // 오류. 여기서 this 는 vue instance 가 아닌 window
// mounted, udpated, destroyed 마찬가지.

methods: {
  methodA: () => {  // arrow function 사용하면 안됨
    // this 는 window
    alert(this == window) // true
    this.methodB() // 오류
  },
  methodB: function(){
    // this 는 현재 vue instance
    this.methodA() // 정상
  },
  methodC() {
    this.methodA() // 정상
  }
}

 

 

왜?

Each Vue instance goes through a series of initialization steps when it’s created - for example, it needs to set up data observation, compile the template, mount the instance to the DOM, and update the DOM when data changes. Along the way, it also runs functions called lifecycle hooks, giving users the opportunity to add their own code at specific stages.

각 Vue 인스턴스는 생성 될 때 일련의 초기화 단계를 거칩니다. 예를 들어 데이터 관찰을 설정하고, 템플릿을 컴파일하고, 인스턴스를 DOM에 마운트하고, 데이터가 변경되면 DOM을 업데이트해야합니다. 그 과정에서 라이프 사이클 후크라는 함수도 실행하여 사용자에게 특정 단계에서 자신의 코드를 추가 할 수있는 기회를 제공합니다.

For example, the created hook can be used to run code after an instance is created:

예를 들어 created 인스턴스가 생성 된 후 코드를 실행하는 데 후크를 사용할 수 있습니다.

new Vue({
  data: {
    a: 1
  },
  created: function () {
    // `this` points to the vm instance
    console.log('a is: ' + this.a)
  }
})
// => "a is: 1"

 

There are also other hooks which will be called at different stages of the instance’s lifecycle, such as mounted, updated, and destroyed. All lifecycle hooks are called with their this context pointing to the Vue instance invoking it.

인스턴스 수명주기의 여러 단계에서 호출되는 다른 후크 (예 : mounted, updated)도 destroyed있습니다. 모든 수명주기 후크는 this컨텍스트를 호출하는 Vue 인스턴스를 가리키는 컨텍스트로 호출됩니다.

 

Don’t use arrow functions on an options property or callback, such as 
created: () => console.log(this.a) or 
vm.$watch('a', newValue => this.myMethod()). Since an arrow function doesn’t have a this, this will be treated as any other variable and lexically looked up through parent scopes until found, often resulting in errors such as 
Uncaught TypeError: Cannot read property of undefined or 
Uncaught TypeError: this.myMethod is not a function.
사용하지 않는 기능을 화살표 등의 옵션 속성 또는 콜백에  
created: () => console.log(this.a) 또는 
vm.$watch('a', newValue => this.myMethod()). 화살표 함수에는 this, this가 없기 때문에 다른 변수로 처리되고 발견 될 때까지 상위 범위를 통해 어휘 적으로 조회되어 종종 
Uncaught TypeError: Cannot read property of undefined 또는 같은 오류가 발생합니다 
Uncaught TypeError: this.myMethod is not a function.

 

참고

공식 사이트 설명

728x90
반응형

댓글