[vue] vue method에서 화살표 함수 사용시 주의 사항 :: 잡다한 프로그래밍
반응형

Vue 에서 ES6 화살표 함수를 적용하려 할 때 다음과 같은 문제가 발생한다.

1. 문제점

created: () => console.log(this.a)  // 오류. this 는 vue instance 가 아닌 window
// 다른 상태 mounted, udpated, destroyed 등 포함
data: () => ({
  item: ''
}),
methods: {
  // 화살표함수
  methodA: () => {
    // this 는 window
    alert(this == window) // true
    this.methodB() // 오류
  },
  // 기존 함수
  methodB: function(){
    // this 는 현재 vue instance
    this.methodA() // 정상
  },
  // 리터럴 축약 함수
  methodC() {
    this.methodA() // 정상
  }
  
  addTodo: () => {
  	console.log(this.item) //undefined
  }
}

2. 원인

화살표 함수의 this는 기존 es5의 function에서의 this와는 다르게 화살표 함수 내부에서는 this를 새로 정의하지 않는다.

즉 화살표 함수 바로 바깥의 함수(혹은 class)의 this를 사용한다. (클로저)

methods: {
  // 화살표함수
  addTodo: () => {
  	console.log(this.item) //undefined
  }
}

methods 객체에서 this가 따로 만들어져 있지 않으므로 this는 window 객체를 의미하고 vue data를 찾지 못하게 된다.


3. 추가 내용

new Vue({
	el: "#app",
  data: {
    originalNumber: 0,
    arrowNumber: 0,
  },
  methods : {
    originalFunction: function () {
      setTimeout(function () { // 기존함수 선언법
      	console.log('original timeout')
      	this.originalNumber = 3
      }, 3000)
    },
    arrowFunction: function () {
      setTimeout(() => { // 화살표 함수
      	console.log('arrow timeout')
      	this.arrowNumber = 3
      }, 3000)
    }
  }
})

반대로 함수 안에 화살표함수와 function()을 사용했을때는 어떨까?

 

결과는 function()은 오류가나고, 화살표 함수는 정상 동작한다.

 

화살표함수의 this.는 상위 메소드의 this 즉 vue 인스턴스를 가르키고 있고, function()의 this는 vue가 아닌 새로운 function()함수를 가르키고있기 때문이다

반응형

+ Recent posts