vue实现购物车功能

vue实现购物车功能

🍅程序员小王的博客:程序员小王的博客
🍅 欢迎点赞 👍 收藏 ⭐留言 📝
🍅 如有编辑错误联系作者,如果有比较好的文章欢迎分享给我,我会取其精华去其糟粕
🍅java自学的学习路线:java自学的学习路线

原理分析和实现

注意想实现该功能,需要学习:Vue学习之路(基础篇),深入的了解每个指令的使用
首先,还是先把布局写好,和引入vue,准备vue实例,这个不多说,代码如下

<!DOCTYPE html>
<html lang="en" xmlns:v-bind="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>vue实现购物车</title>
</head>
<body>

<div id="app">
    <h3>购物车</h3>
    名称:<input style="width:60px" type="text" v-model="nameValue"> <br/>
    单价:<input style="width:60px" type="text" v-model="priceValue"> <br/>
    数量:<input style="width:60px" type="text" v-model="countValue">
    <button @click="add()">添加购物车</button>
    <hr/>
    <table border="1">
        <tr>
            <td>名称</td>
            <td>单价</td>
            <td>数量</td>
            <td>小计</td>
        </tr>

        <tr v-for="(product,index) in products">
            <td>{{product.name}}</td>
            <td>{{product.price}}</td>
            <td>
                <button @click="desc(index)">-</button>
                {{product.count}}
                <button @click="incr(index)">+</button>
            </td>
            <td>{{product.price*product.count}}</td>
        </tr>

        <tr>
            <td colspan="4">总价:{{total()}}元</td>
        </tr>
    </table>
</div>
</body>
</html>
<script src="js/vue-min.js"></script>
<script>
    new Vue({
        el: "#app",
        data: {
            products: [
                {name: "秋裤", price: "81", count: 2},
                {name: "华为", price: "5810", count: 1},
            ],
            nameValue: "",
            priceValue: "",
            countValue: 0,
            totalPrice:0
        },
        methods: {
            incr(index) {
                this.products[index].count++;
            },
            desc(index) {
                this.products[index].count--;
            },
            add() {
                this.products.push({name: this.nameValue, price: this.priceValue, count: this.countValue});
                this.nameValue = "";
                this.priceValue = "";
                this.countValue = 0;
            },
            total(){

                var price=0;

                for (var i = 0; i <this.products.length; i++) {

                    price+=this.products[i].price * this.products[i].count
                }

                return price.toFixed(2);
            }
        }
    })

</script>

  • 5
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序员小王java

学习java的路上,加油!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值