这一篇把之前所学的内容做一个总结,实现一个购物车样例,可以增加或者减少购买数量,可移除商品,并且购物车总价随着你的操作实时变化。

实现效果如图:

代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>购物车案例</title>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <style>
        [v-cloak] {
            display: none;
        }
        table {
            border: 1px solid #e9e9e9;
            border-collapse: collapse;
            border-spacing: 0;
            empty-cells: show;
        }
        th, td {
            padding: 8px 16px;
            border: 1px solid #e9e9e9;
            text-align: left;
        }
        th {
            background-color: #f7f7f7;
            color: #5c6b77;
            font-weight: 600;
            white-space: nowrap;
        }
    </style>

</head>
<body>
<div id="app" v-cloak>
    <table>
        <tr>
            <th>序列号</th>
            <th>商品名称</th>
            <th>商品单价</th>
            <th>购买数量</th>
            <th>操作</th>
        </tr>
        <tr v-for="(item, index) in list">
            <td>{{ index + 1 }}</td>
            <td>{{ item.name }}</td>
            <td>{{ item.price }}</td>
            <td>
                <button @click="reduce(index)" :disable="item.count === 1">-</button>
                {{ item.count }}
                <button @click="add(index)">+</button>
            </td>
            <td><button @click="del(index)">移除</button></td>
        </tr>
    </table>
    <p>总价:¥{{ total }}</p>
</div>
<script>
    var app = new Vue({
        el: '#app',
        data: {
            list: [
                {
                    id: 1,
                    name: 'Iphone xs',
                    price: 10000,
                    count: 1
                },
                {
                    id: 2,
                    name: 'Ipad Pro',
                    price: 6666,
                    count: 1
                },
                {
                    id: 3,
                    name: 'MacBook Pro',
                    price: 25000,
                    count: 1
                },
            ]
        },
        methods: {
            reduce: function (index) {
                if(this.list[index].count === 1) return;
                this.list[index].count--;
            },
            add: function (index) {
                this.list[index].count++;
            },
            del: function (index) {
                this.list.splice(index, 1);
            }
        },
        computed: {
            total: function () {
                var total = 0;
                for(var i = 0; i < this.list.length; i++) {
                    total += this.list[i].price * this.list[i].count;
                }
                return total.toString().replace(/\B(?=(\d{3})+$)/g, ',');
            }
        }
    });
</script>
</body>
</html>

posted on 2018-11-20 22:20  kindleheart  阅读(1689)  评论(0编辑  收藏  举报