【Vue】实现简单的购物车页面

效果预览:https://sevlt.github.io/shopping-cart/index.html

Html 代码:

<!DOCTYPE html>
<html lang="zh-CN">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <link rel="stylesheet" href="./style.css" />
        <script src="./vue.js"></script>
        <title>Shopping Cart</title>
    </head>
    <body>
        <div id="app">
            <table>
                <tr>
                    <th>序号</th>
                    <th>商品名称</th>
                    <th>单价</th>
                    <th>数量</th>
                    <th>操作</th>
                </tr>
                <tr v-for="product in products">
                    <td>{{product.id}}</td>
                    <td>{{product.name}}</td>
                    <td>${{product.price}}</td>
                    <td>
                        <button v-bind:disabled="product.count===0" v-on:click="product.count-=1">
                            -
                        </button>
                        {{product.count}}
                        <button v-on:click="product.count+=1">
                            +
                        </button>
                    </td>
                    <td><button v-on:click="product.count=0">归零</button></td>
                </tr>
                <tr>
                    <td colspan="5" class="no">总价:${{totalPrice()}}</td>
                </tr>
            </table>
        </div>
        <script src="./main.js"></script>
    </body>
</html>

CSS 代码:

#app {
    position: relative;
    display: flex;
    justify-content: center;
}
table {
    position: absolute;
    width: 50%;
    border: 1px solid black;
    border-radius: 7px;
    top: 70px;
}
th {
    height: 50px;
}
td {
    height: 30px;
    text-align: center;
    border-bottom: 1px solid #ddd;
}
.no {
    text-align: right;
    padding-right: 20px;
    border-bottom: none;
}

JavaScript 代码:

var vm = new Vue({
    el: '#app',
    data: {
        products: [
            { id: 1, name: 'iPhone 11', price: 699, count: 1 },
            { id: 2, name: 'iPhone 11 Pro', price: 999, count: 1 },
            { id: 3, name: 'iPhone 11 Pro Max', price: 1099, count: 1 },
        ],
    },
    methods: {  
        totalPrice: function () {
            var num = 0
            for (var i = 0; i < this.products.length; i++) {
                num += this.products[i].count * this.products[i].price
            }
            return num
        },
    },
})

 


版权声明:本文为sunqi568原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。