체크박스의 값(handleCheck(idx))이 true 로 @change 했을때
tmp.sum 에 tmp.price * tmp.cnt 값을 표시함.
// idx는 items의 숫자? 순서? 를 나타냄.
// v-for="(tmp, idx)~ 로 idx = 0 1 2 3 ... length of items 를 뜻함.
미리 계산 해서 화면에 표시
<template>
<div class="container">
<h3>주문목록</h3>
<hr>
<table border="1">
<thead>
<tr>
<th>체크</th>
<th>아이디</th>
<th>나이</th>
<th>가격</th>
<th>수량</th>
<th>합계</th>
</tr>
</thead>
<tbody>
<tr v-for="(tmp, idx) in items" v-bind:key="tmp">
<td>
<input type="checkbox" v-model="tmp.chk"
@change="handleCheck(idx)" />
</td>
<td>{{ tmp.id }}</td>
<td>{{ tmp.age }}</td>
<td>{{ tmp.price}}</td>
<td>
<select v-model="tmp.cnt1" @change="handleCheck(idx)">
<option v-for="tmp1 in tmp.cnt" v-bind:key="tmp1">
{{tmp1}}
</option>
</select>
<!-- {{ tmp.cnt }} -->
</td>
<td v-text="tmp.sum"></td>
</tr>
<tr>
<td colspan="2">합계</td> <!-- colspan="2" 두칸 합치기 -->
<!-- <td></td> 합쳤으니 한칸 없애야 됨-->
<td>{{ sumAge }}</td>
<td>{{ sumPrice }}</td>
<td></td>
<td>{{ sumTotal }}</td>
</tr>
</tbody>
</table>
</div>
</template>
<script>
export default {
// 생명주기 (자동호출)
created() {
this.handleData();
},
mounted() {
},
// 미리계산 (생명주기 + 메소드)
computed : {
sumAge() {
let sum = 0;
for(let tmp of this.items) {
sum += tmp.age;
}
// console.log(sum);
return sum;
},
sumPrice() {
let sum = 0;
for(let tmp of this.items) {
sum += tmp.price;
}
// console.log(sum);
return sum;
},
sumTotal() {
let sum = 0;
for(let tmp of this.items) {
sum += tmp.sum;
}
// console.log(sum);
return sum;
}
},
// 상태변수
data() {
return {
items : [],
}
},
// 메소드, 함수
methods : {
handleCheck(idx) { // idx는 0부터 시작, 외우지말고 매번 확인해야함
console.log('Table1.vue => handleCheck', idx+1);
// handleCheck 메소드를 실행하겠다고 정의해서, @change 하면 위의 메세지가 콘솔로그에 뜸
if(this.items[idx].chk === true) {
this.items[idx].sum =
this.items[idx].price * this.items[idx].cnt1;
}
else {
this.items[idx].sum = 0;
}
},
async handleData() {
// 백엔드로부터 데이터를 받았다고 가정
this.items = [
{ id:'a1', age:34, price:123, cnt:23 },
{ id:'a2', age:13, price:13, cnt:13 },
{ id:'a3', age:27, price:234, cnt:55 },
{ id:'a4', age:55, price:76, cnt:35 },
{ id:'a5', age:8, price:983, cnt:19 },
];
// for 배열의 번호를 반복 0 1 2 3 4 둘다 같은데 둘다 알아야함
for(let i=0; i<this.items.length; i++){ // 0 1 2 3 4
this.items[i]['chk'] = false;
this.items[i]['sum'] = 0;
this.items[i]['cnt1'] = 1;
}
// // forEach 배열내의 내용을 1개씩 복사
// for(let tmp of this.items) {
// tmp['chk'] = false; //{id: 'a2', age: 13, price: 13, cnt: 3, chk: false}
// }
// 백엔드에서 받은 값 출력 [{},{},{},{},...{}]
console.log(this.items); //{id: 'a2', age: 13, price: 13, cnt: 3, chk: false}
}
}
}
</script>
<style scoped>
@import '../assets/css/mystyle1.css';
</style>