购物车案例
<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>