본문 바로가기
보드게임 긱 추천 게임
Wizard Thumbnail
BoardGameGeek 사이트에서 인기순위 상위 100개 중 랜덤 3개를 보여줍니다.
BGG
귀펀치토끼는 부서지지 않는다.
주소(D)
영웅은 공부 따원 안 한다네/뷰

[Vue3] NaN 방어코드

사용자가 input 박스에 값을 입력하면 합계를 자동으로 출력하는 코드를 만들었다.

문제1. 숫자가 아닌 값(string 또는 null)이 들어갈 경우 합계가 NaN이 나온다.

우선 <input type="number">를 추가해 오직 숫자만 입력될 수 있도록 했다.

문제2. Backspace를 넣을 경우(null) NaN이 나오는데 값이 없을 때 0으로 인식하게 했다.

 

    string이 들어갈 수 없도록 방지

<label for="rent">
  <input
    :value="item.cmsQuantity"
    type="number"
    @input="changeCmsQuantity($event, index)"
  >
</label>
<p>
  {{ getCmsTotal(index) }}
</p>

 

    Number.isNaN으로 null일 때 0으로 인식되도록 함  

// 수량 수정
const changeCmsQuantity = (e: Event, index: number) => {
  const target = e.target as HTMLInputElement;
  cmsItemList[index].cmsQuantity = target.valueAsNumber;
  if (Number.isNaN(cmsItemList[index].cmsQuantity)) {
    cmsItemList[index].cmsQuantity = 0;
  }
};
// 금액 계산
const getCmsTotal = (index: number) => {
  cmsItemList[index].cmsTotal = Math.floor(cmsItemList[index].cmsPrice * cmsItemList[index].cmsQuantity);
  if (Number.isNaN(cmsItemList[index].cmsTotal)) {
    return 0;
  }
  return cmsItemList[index].cmsTotal.toLocaleString('ko-KR');
};
완료
내 컴퓨터