배경설명
- select 반팝업 출력 시, 선택된 항목 체크 표시 출력을 위해 selected="true" 속성 설정 필요
이슈
- select 반팝업 출력 직후, List 내 객체에 isSelected 속성 신규 추가
for (const item of this.pdList) {
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 활용하여 객체 내 상태 변경 감지 가능한 속성 추가
for (const item of this.pdList) {
this.$set(item, 'isSelected', (selectedPdId === item.id));
}
참고