@change="fun"
:元素值发生改变时,会触发事件fun
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="app">
<table>
<thead>
<tr>
<!-- 全选 -->
<td><input type="checkbox" @click="selectAll" v-model="data.selected"></td>
<td>商品名称</td>
<td>商品价格</td>
<td>库存</td>
<!-- colspan2: 单元格跨度为2 -->
<td colspan="2">操作</td>
</tr>
</thead>
<tbody>
<tr v-for="(item, index) in data.list" :key="item.id">
<td>
<input type="checkbox" :value="item" v-model="data.checkboxList" @change="checkSelect">
</td>
<td>{{item.name}}</td>
<td>{{item.price}}</td>
<td>{{item.stock}}</td>
<td>
<button @click="sub(item)">-</button>
{{item.number}}
<button @click="add(item)">+</button>
</td>
<td>
<button @click="del(index,item.id)">删除</button>
</td>
</tr>
</tbody>
<tfoot>
<tr>
<td>总价格: {{totalPrice()}}</td>
</tr>
</tfoot>
</table>
</div>
<script type="module">
import { createApp, reactive, ref } from './vue.esm-browser.js'
createApp({
setup() {
const data = reactive({
selected: false,//全选?
checkboxList: [],//购物车中的商品
list: [{
id: 1,//编号
name: '洗衣机',//名字
price: 10000,//价格
number: 1,//数量
stock: 10//库存
},
{
id: 2,
name: '电冰箱',
price: 20000,
number: 2,
stock: 8
},
{
id: 3,
name: '空调',
price: 30000,
number: 3,
stock: 6
},
{
id: 4,
name: '电视',
price: 40000,
number: 4,
stock: 4
},
{
id: 5,
name: '微波炉',
price: 50000,
number: 5,
stock: 20
}
]
})
//全选/反选
const selectAll = () => {
data.selected = !data.selected
if (data.selected) {//全选
data.checkboxList = data.list
}
else {//反选
data.checkboxList = []
}
}
//取消一个物品时候,自动取消全选
const checkSelect = () => {
if (data.checkboxList.length == data.list.length && data.list.length != 0) {
data.selected = true
}
else {
data.selected = false
}
}
//计算总价格
const totalPrice = () => {
let total = 0
for (let i = 0; i < data.checkboxList.length; i++) {
total += data.checkboxList[i].price * data.checkboxList[i].number
}
return total
}
//增加物品数量
const sub = (value) => {
value.number--
if (value.number < 1) {
value.number = 1
}
}
//减少物品数量
const add = (value) => {
value.number++
if (value.number > value.stock) {
value.number = value.stock
}
}
//删除物品
const del = (index, id) => {
data.list.splice(index, 1)
//过滤器:筛选元素,返回新的数组
let newArr = data.checkboxList.filter((value, index) => {
return value.id != id//删除id相同的元素
})
data.checkboxList = newArr
}
return {
data,
selectAll,
checkSelect,
totalPrice,
sub,
add,
del
}
}
}).mount("#app")
</script>
</body>
</html>
参考
https://www.bilibili.com/video/BV1nV411Q7RX