购物车案例(vue)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<script src="js/vue221.js"></script>
<body>
    <div id="app">
        <table border="1" cellspacing="0">
            <tr>
                <th>商品名称</th>
                <th>商品单价</th>
                <th>商品数量</th>
                <th>小计</th>
            </tr>
            <tr v-for="(item,index) in goodsList">
                <td>
                    {{item.name}}
                </td>
                <td>
                    {{item.price}}
                </td>
                <td>
                    <button @click="reduceCount(index)">-</button>
                    {{item.count}}
                    <button @click="addCount(index)">+</button>
                </td>
                <td>
                    {{item.count*item.price}}
                </td>
            </tr>
            <tr>
                <td>
                    总数量:
                </td>
                <td>
                    {{totalCount}}
                </td>
                <td>
                    总价格:
                </td>
                <td>
                    {{totalPrice}}
                </td>
            </tr>
        </table>
    </div>
</body>
<script>
    //商品: 名称  单价  数量 
    //使用对象来进行存储  {name:"篮球鞋",price:500,count:1}
    //总数量不是固定数据,根据每一个商品的数量 运算得出的 在vue中 属于计算属性
    //计算属性 :通过计算 得出新的属性
    let vm=new Vue({
        el:"#app",
        data:{
            goodsList:[
                {name:"篮球鞋",price:500,count:1},
                {name:"队服",price:200,count:3},
                {name:"电脑",price:5000,count:2}
            ]
        },
        methods:{
            addCount(index){
                //找到对应的对象 将其count++
                this.goodsList[index].count++
            },
            reduceCount(index){
               if(this.goodsList[index].count>0){
                   this.goodsList[index].count--
                } 
            }
        },
       computed:{
           //定义一个新的名称
        totalCount(){
            //依次拿出数组中的每个商品对象让其求和
            let sum = 0
            for(let n = 0;n<this.goodsList.length;n++){
                sum=sum+this.goodsList[n].count
            }
            return sum
        },
        totalPrice(){
            let sum=0
            for(let n=0;n<this.goodsList.length;n++){
                sum=sum+this.goodsList[n].price*this.goodsList[n].count
            }
            return sum
        }
       }
    })
</script>
</html>

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值