最终效果展示:支持搜索,支持物品数量添加,支持删除等操作,总价会随着数量和删除的操作发生变化,最适合新手练习Vue3用了
实现的案例代码:
<template>
<div>
<h2>1024小神的购物车</h2>
<div><input v-model="search" type="text" /><button>搜索</button></div>
<div>
<table border width="600" cellspacing="0" style="margin-top: 10px">
<thead>
<th>物品名称</th>
<th>物品单价</th>
<th>物品数量</th>
<th>物品总价</th>
<th>操作</th>
</thead>
<tbody>
<tr v-for="(good, index) in searchData" :key="index">
<td align="center">{
{ good.name }}</td>
<td align="center">{
{ good.price }}</td>
<td align="center">
<button @click="good.num > 1 ? good.num-- : 1">-</button>
{
{ good.num }}
<button @click="good.num++">+</button>
</td>
<td align="center">{
{ good.total }}</td>
<td align="center"><button @click="deleteGood(index)">删除</button></td>
</tr>
<tr>
<td colspan="5" align="right">总价:{
{ total }}</td>
</tr>
</tbody>
</table>
</div>
</div>
</template>
<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
// 搜索商品
const search = ref('')
const searchData = computed(() => {
return goodData.filter((item) => {
return item.name.includes(search.value)
})
})
// 删除商品
const deleteGood = (index:number)=>{
goodData.splice(index, 1)
}
// 定义商品
type good = {
name: string
price: number
num: number
total: number
}
// 商品数据列表
const goodData = reactive<good[]>([
{
name: '苹果手机',
price: 1500,
num: 1,
total: 1500
},
{
name: '安卓手机',
price: 500,
num: 1,
total: 500
},
{
name: '游戏机',
price: 100,
num: 1,
total: 100
},
{
name: '大屏电视',
price: 1000,
num: 1,
total: 1000
}
])
// 定义计算属性计算总价
const total = computed(() => {
return goodData.reduce((pre, cur) => {
return pre + cur.price * cur.num
}, 0)
})
</script>
<style scoped></style>