演练:实现购物车功能
<template>
<input type="text" class="inp" placeholder="搜索" v-model="keywords">
<div>
<table border="1" cellspacing="0" width="400" height="150">
<thead>
<tr>
<th>物品名称</th>
<th>单价</th>
<th>数量</th>
<th>物品总价</th>
<th>操作</th>
</tr>
</thead>
<tbody class="abc">
<tr v-for="(item,index) in searchData" :key="item.name">
<td>{{ item.name }}</td>
<td>{{ item.price }}</td>
<td>
<button @click="item.number>0 ? item.number--: 0">-</button>
{{ item.number }}
<button @click="item.number<10 ? item.number++:99">+</button>
</td>
<td>{{ item.price*item.number }}</td>
<td> <button @click="handleDelete(index)">{{ item.delete }}</button></td>
</tr>
<tr>累积总价:{{ total }}</tr>
</tbody>
</table>
</div>
</template>
<script setup>
import { ref,reactive,computed} from 'vue'
const data = reactive([{
name:'张三的绿帽子',
price:500,
number:1,
delete:'删除'
},
{
name:'张三的红衣服',
price:10,
number:1,
delete:'删除'
},
{
name:'张三的黑袜子',
price:999,
number:1,
delete:'删除'
}])
//操作删除
const handleDelete = (index)=>{
data.splice(index,1)
}
//累积总价
const total = computed(()=>{
return data.reduce((a,b)=>{
return a + b.price*b.number
},0)
})
let keywords = ref('');
//搜索
const searchData = computed(()=>{
return data.filter(item=> item.name.includes(keywords.value))
})
</script>
<style scoped>
.abc{
text-align: center;
}
.inp{
margin-bottom: 5px;
width:200px
}
</style>