[vuejs] data 객체 object 추가/제거 속성 변경 상태 관리하는 방법

Jinbro·2023년 12월 13일
0

Vuejs

목록 보기
9/9

배경설명

  • select 반팝업 출력 시, 선택된 항목 체크 표시 출력을 위해 selected="true" 속성 설정 필요

이슈

  • select 반팝업 출력 직후, List 내 객체에 isSelected 속성 신규 추가
// ASIS
for (const item of this.pdList) {
  // item 객체는 isSelected 속성이 없음 -> 신규 추가
  item.isSelected = (selectedPdId === item.id);
}
  • 추가된 isSelected 속성 vue 데이터 변경 감지 못 함
<li v-for="(pdItem, idx) in pdList" :key="pdItem.id">
  <button type="button" :class="{ 'selected': pdItem.isSelected }"></button>
  ...
</li>

원인

  • vue 인스턴스 초기화 단계에서 data 객체를 전달하면 Vue는 모든 속성을 getter/setter로 변환하여 데이터의 변경을 감지할 수 있음
  • vue는 data object 객체에 동적으로 추가 제거된 속성은 감지 할 수 없다!

해결방법

  • vue.$set 활용하여 객체 내 상태 변경 감지 가능한 속성 추가
// TOBE
for (const item of this.pdList) {
  this.$set(item, 'isSelected', (selectedPdId === item.id));
}

참고

profile
자기 개발 기록 저장소

0개의 댓글