购物车案例
<template>
<div class="container">
<h1>总价:{{total}}</h1>
<table border style="width: 500px">
<thead>
<tr>
<th>名称</th>
<th>数量</th>
<th>单价</th>
<th>价格</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr v-for="(item,index) in data" :key="index">
<td>{{ item.name }}</td>
<td>
<button @click="add(item, false)">-</button>
{{ item.num }}
<button @click="add(item, true)">+</button>
</td>
<td>
{{ item.price }}
</td>
<td>{{ item.num * item.price }}</td>
<td><button @click="del(item,index)">删除</button></td>
</tr>
</tbody>
</table>
</div>
</template>
<script setup lang="ts">
import { reactive, ref, computed } from "vue";
interface Shops {
name: string;
num: number;
price: number;
}
const add = (good: Shops, flag: boolean) => {
if (flag) {
good.num++;
} else {
good.num--;
}
};
const total = computed<number>(() => {
return data.reduce((prev,next)=>{
return prev + (next.num * next.price)
},0)
})
const del = (item:Shops,index:number) => {
data.splice(index,1)
}
const singlePrice = computed(() => {});
const data = reactive<Shops[]>([
{
name: "小飞",
num: 1,
price: 12,
},
{
name: "小马",
num: 1,
price: 20,
},
{
name: "小龙",
num: 1,
price: 30,
},
]);
</script>
<style lang="scss" scoped></style>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 80
- 81
- 82
- 83