1. LWC 반복문
- < template for:each=" 리스트 " for:item=" 현재 대상 " >
<template for:each={productList} for:item="pli" >
</template>
2. <for:index=" 인덱스 " > 추가
- < template for:each=" " for:item=" " for:index = " 인덱스 " >
<template for:each={productList} for:item="pli" for:index="index">
</template>
3. 반복되는 행에 index 및 event 부여
- data-index={인덱스}
- onclick = {이벤트}
<template for:each={productList} for:item="pli" for:index="index">
<tr key={pli.Id} >
<td><lightning-input type="checkbox" name={pli.Id} data-index={index} onclick={addOrderList}></lightning-input></td>
<td>{pli.Name}</td>
<td>{pli.UnitPrice}</td>
</tr>
</template>
4. event로 부여한 index 가져오기 및 활용
- index 체크 -> const index = event.target.dataset.index;
- index 활용 -> this.리스트[index];
//js파일
addOrderList(event){
const index = event.target.dataset.index;
console.log('Checkbox clicked on row with index:', index);
console.log(this.productList[index]);
}
5. 코드확인
//html 파일
<div class="table-outer slds-scrollable" style="height: 200px;">
<table class="slds-table slds-table_bordered slds-table_cell-buffer">
<thead style="text-align:center;">
<tr class="slds-text-heading_label">
<th scope="col">선택</th>
<th scope="col">상품명</th>
<th scope="col">금액</th>
</tr>
</thead>
<tbody style="text-align:center;">
<template for:each={productList} for:item="pli" for:index="index">
<tr key={pli.Id} >
<td><lightning-input type="checkbox" name={pli.Id} data-index={index} onclick={addOrderList}></lightning-input></td>
<td>{pli.Name}</td>
<td>{pli.UnitPrice}</td>
</tr>
</template>
</tbody>
</table>
</div>
//js파일
addOrderList(event){
const index = event.target.dataset.index;
console.log('Checkbox 클릭한 행의 index :', index);
console.log(this.productList[index]);
}
+ this.producList[index].UnitPrice = 1000; 식으로 활용