Vue3中使用ref, reactive, computed完成的购物车案例,使用chatgpt写的
最终效果展示:支持搜索,支持物品数量添加,支持删除等操作,总价会随着数量和删除的操作发生变化,最适合新手练习Vue3用了。
·
最终效果展示:支持搜索,支持物品数量添加,支持删除等操作,总价会随着数量和删除的操作发生变化,最适合新手练习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>

GitCode 天启AI是一款由 GitCode 团队打造的智能助手,基于先进的LLM(大语言模型)与多智能体 Agent 技术构建,致力于为用户提供高效、智能、多模态的创作与开发支持。它不仅支持自然语言对话,还具备处理文件、生成 PPT、撰写分析报告、开发 Web 应用等多项能力,真正做到“一句话,让 Al帮你完成复杂任务”。
更多推荐
所有评论(0)