개발자 노트

[Vue] object method에서 this가 undefined로 나오는 이슈 본문

▶ FRONT-END ◀

[Vue] object method에서 this가 undefined로 나오는 이슈

heeyam 2023. 1. 10. 00:32
반응형

환경: vue 3.x, script setup

-- 문제 --

custom event 즉, 하위 컴포넌트에서 emit으로 전달된 이벤트를 상위 컴포넌트에서 받아서 사용하려는 상황이다. 이 때, 하위 컴포넌트에서 받아온 emit event에 object (객체) method 를 바인딩하였고, method에서 this를 사용해 객체 안에 있는 프로퍼티 값을 변경하려고 했다.

코드는 다음과 같다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// 상위 컴포넌트
<script setup>
import ChildComponent from '하위 컴포넌트 경로';
const obj = {
  print() {
    console.log(this);
  },
};
</script>
 
<template>
<child-component
  @custom-event="obj.print"
/>
</template>
cs

위의 코드처럼 custom event에 객체 method 이름을 바인딩하여 실행하면 브라우저 콘솔창에서 undefined가 출력된다.


-- 해결 --

1
@custom-event="obj.print()"
cs

위의 코드처럼 custom event에 객체 method 이름만 바인딩하는 것이아닌 호출까지 하면 브라우저 콘솔창에서는 obj 가 출력된다.

참고로, 상위 컴포넌트의 template 에서 기본태그(div, input, button 등) 에 DOM 이벤트(click, input, change 등) 를 핸들링하기 위해 아래 코드처럼 object method 이름만 바인딩을 해도 이 경우에는 this는 obj를 가리켰다. 

1
2
3
4
5
6
7
8
9
10
11
12
13
<script setup>
const obj = {
  print() {
    console.log(this);
  },
};
</script>
 
<template>
<button
  @click="obj.print"
> Click </button>
</template>
cs

물론 이 때 object method를 호출하더라도 this는 obj를 가리켰다.

1
2
3
<button
  @click="obj.print()"
> Click </button>
cs

 

따라서... 🤔 Vue에서 기본 DOM 이벤트와 custom 이벤트 처리가 내부적으로 다르게 동작하고 있다고 추측해본다.

자바스크립트에서 this는 함수를 호출할 때 어디서, 어떻게 호출했는지에 영향을 받기 때문에 custom 이벤트에 객체 method의 이름만 바인딩할 때는 해당 method가 호출되는 시점에서 method 내부의 this가 전역객체를 가리키고 있기 때문에 undefined로 표시되고 있는 것 같다.


-- 참고 문서 --

- vue event handling

반응형
Comments