vue3(七) computed计算属性 小练习

 演练:实现购物车功能

<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>

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值