JS模块化实战-购物车
HTML示范代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>购物车</title>
<link rel="stylesheet" href="static/css/cart.css" />
</head>
<body>
<div class="cart">
<table>
<caption>
我的购物车
</caption>
<thead>
<tr>
<td><input type="checkbox" name="check-all" /></td>
<td>编号</td>
<td>品名</td>
<td>单位</td>
<td>单价</td>
<td>数量</td>
<td>金额</td>
</tr>
</thead>
</table>
</div>
<script type="module">
//(一)商品信息
const items = [
{ id: 286, name: '酸奶', units: '箱', price: 50, num: 1 },
{ id: 870, name: '苹果', units: '千克', price: 10, num: 1 },
{ id: 633, name: '外-套', units: '件', price: 300, num: 6 },
{ id: 153, name: '皮鞋', units: '双', price: 400, num: 2 },
{ id: 109, name: '手机', units: '台', price: 5000, num: 1 },
];
//(二) 导入购物车模块
import Cart from './modules/cart.js';
//(三) 实例化购物车类
const cart = new Cart(items);
//(四) 获取购物车(表格)
const table = document.querySelector('table');
//(五) 将商品渲染到购物车元素中 tbody
const tbody = table.createTBody();
items.forEach(function (item, key) {
//1. 创建模板字符串:tr
const tr = `
<tr>
<td><input type = "checkbox" name = "check" checked></td>
<td>${item.id}</td>
<td>${item.name}</td>
<td>${item.units}</td>
<td>${item.price}</td>
<td><input type = "number" name = "" value = "${item.num}"</td>
<td class="money">${cart.money[key]}</td>
</tr>
`;
//2.将内容填充到tbody,将模板字符串解析成html并添加到tbody中
tbody.insertAdjacentHTML('beforeend', tr);
});
//(六) 将相关统计数据(总数量,总金额)添加到tfoot中
const tfoot = table.createTFoot();
let tr = `
<tr>
<td colspan="5">总计:</td>
<td class = "total">${cart.total}</td>
<td class = "total-money">${cart.totalMoney}</td>
</tr>
`;
tfoot.insertAdjacentHTML('beforeend', tr);
//(七) 更新数量,实时计算出结果并显示出来
//(1).拿到所有的数量控件
const nums = table.querySelectorAll('input[type=number]');
//(2).为每一个数量控件添加事件监听:input
nums.forEach(function (num, key) {
num.oninput = function () {
//1.计算总数量
items[key].num = num.value * 1;
cart.total = cart.getTotal(items);
//2.计算每个商品金额
cart.money[key] = num.value * 1 * items[key].price;
//3.计算商品总金额
cart.totalMoney = cart.money.reduce((acc,cur) => acc + cur);
//4.将数据渲染到指定元素
table.querySelector('.total').textContent = cart.total;
table.querySelector('.total-money').textContent = cart.totalMoney;
table.querySelectorAll('.money')[key].textContent = cart.money[key];
};
});
</script>
</body>
</html>
JS示范代码
//默认导出
//购物车模块
export default class {
//构造器
constructor(items) {
//1.商品总数量
this.total = this.getTotal(items);
//2.每个商品金额(数组)
this.money = this.getMoney(items);
//3.商品总金额
this.totalMoney = this.getTotalMoney();
}
getTotal(items) {
//1.数量数组:每个商品的数量num字段组成的数组
//forEach没有返回,map也是循环,但有返回
let numArr = items.map((item) => item.num);
// console.log(numArr);
//2.数组求和
return numArr.reduce((acc, cur) => acc + cur);
}
getMoney(items) {
return items.map((item) => item.price * item.num);
}
getTotalMoney(items) {
return this.money.reduce((acc, cur) => acc + cur);
}
}