Vue实现购物车全选及价格计算

6 篇文章 1 订阅

《vuejs实战》这本书中5.5是一道实战题:利用计算属性、指令等知识开发购物车。

练习1:在当前示例基础上扩展商品列表,新增一项是否选中该商品的功能,总价变为只计算选中商品的总价,同时提供一个全选的按钮。

练习2:将商品列表list改为一个二维数组来实现商品的分类,比如可分为“电子产品” “生活用品” 和“果蔬”,同类商品聚合在一起。提示,你可能会用到两次v-for。

1、购物车 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        [v-cloak] {
            display: none;
        }
        table{
            border: 1px solid #e9e9e9;
            border-collapse: collapse;
            border-spacing: 0;
            empty-cells: show;
            padding: 10px;
        }
        th, td{
            border: 1px solid #e9e9e9;
            text-align: left;
            padding: 10px;
        }
        th{
            background: #f7f7f7;
            color: #5c6b77;
            font-weight: 600;
            white-space: nowrap;
            padding: 10px;
        }
    </style>
</head>
<body>
    <div id="app" v-cloak>
        <template v-if="list.length">
            <table>
                <thead>
                    <tr>
                        <th>
                            <span>全选</span>
                            <input type="checkbox" @click="checkedAll(),checkModel()" v-model="checked">
                        </th>
                        <th>编号</th>
                        <th>商品名称</th>
                        <th>商品单价</th>
                        <th>购买数量</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    <tr v-for="(item, index) in list">
                        <td>
                            <input type="checkbox" :value="item.id" v-model="checkBoxModel" @click.stop="onlyChecked(index),checkPick()"> 
                        </td>
                        <td>{{ index + 1}}</td>
                        <td>{{ item.name }}</td>
                        <td>{{ item.price }}</td>
                        <td>
                            <button @click="handleReduce(index)" :disable="item.count === 1">-</button>
                            {{ item.count }}
                            <button @click="handleAdd(index)">+</button>
                        </td>
                        <td>
                            <button @click="handleRemove(index)">移除</button>
                        </td>
                    </tr>
                </tbody>
            </table>
            <div style="margin-top: 20px;">总价:¥{{ totalPrice }}</div>
        </template>
        <div v-else>购物车为空</div>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <script>
    var app = new Vue({
        el: '#app',
        data: {
            list: [
                {
                    id: 1,
                    name: '《我喜欢你,像风走了八千里》',
                    price: 24,
                    count: 1,
                    checked: false
                },
                {
                    id: 2,
                    name: '《余生很长,别慌张,别失望》',
                    price: 25.2,
                    count:1,
                    checked: false
                },
                {
                    id:3,
                    name:'《不堪孤独,就无法脱离庸俗》',
                    price: 23.8,
                    count:1,
                    checked: false
                }
            ],
            checkBoxModel: [],
            checked: false
        },
        computed: {
            totalPrice: function () {
                var total = 0;
                for (var i = 0; i < this.list.length; i++) {
                    if (this.list[i].checked) {
                        var item = this.list[i];
                        total += item.price * item.count;
                    }
                }
                return total.toFixed(2);
            }
        },
        methods: {
            handleReduce: function (index) {
                if (this.list[index].count === 1) return;
                this.list[index].count--;
            },
            handleAdd: function (index) {
                this.list[index].count++;
            },
            handleRemove: function (index) {
                this.list.splice(index, 1);
            },
            //全选的实现通过checkBoxModel的状态
            checkedAll: function () {
                var _this = this;
                if (_this.checked) {
                    _this.checkBoxModel = [];
                    _this.checked = false;
                } else {
                    _this.checkBoxModel = [];
                    _this.list.forEach(function (item) {
                        _this.checkBoxModel.push(item.id);
                    });
                    _this.checked = true;
                }
            },
            //单选的实现依靠的是checked通过click的切换实现
            onlyChecked: function (index) {
                if (this.list[index].checked) {
                    this.list[index].checked = false;
                } else {
                    this.list[index].checked = true;
                }
            },
            // 从遍历单个,若全部选中则全选按钮选中
            checkPick: function () {
                me = this;
                var checkedSum = 0;
                for (var i = 0; i < me.list.length; i++) {
                    if (me.list[i].checked) {
                        checkedSum++;
                    }
                }
                if (checkedSum == me.list.length) {
                    me.checked = true;
                } else {
                    me.checked = false;
                }
            },
            //计算价格
            checkModel: function () {
                me = this;
                if (me.checkBoxModel.length) {
                    newArr = me.checkBoxModel.concat();
                    // console.log(newArr);
                    // console.log(me.checkBoxModel);
                    for (var i = 0; i < me.checkBoxModel.length; i++) {
                        newone = newArr.shift().toString();
                        console.log(newone);
                        me.list[newone - 1].checked = true;
                    }
                } else {
                    newArr = me.checkBoxModel.concat();
                    // console.log(newArr);
                    for (var i = 0; i < me.list.length; i++) {
                        me.list[i].checked = false;
                    }
                }
                // 利用checkBoxModel的绑定的状态来分别给每个物品确认checked的状态,避免与onlyChecked的冲突
            }
        }
    });
    </script>
</body>
</html>

2、二维数组

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        [v-cloak] {
            display: none;
        }
        table{
            border: 1px solid #e9e9e9;
            border-collapse: collapse;
            border-spacing: 0;
            empty-cells: show;
        }
        th, td{
            border: 1px solid #e9e9e9;
            text-align: left;
            padding: 5px;
        }
        th{
            background: #f7f7f7;
            color: #5c6b77;
            font-weight: 600;
            white-space: nowrap;
            padding: 5px;
        }
    </style>
</head>
<body>
    <div id="app" v-cloak>
        <template v-if="list.length">
            <table>
                <thead>
                    <tr>
                        <th>
                            <span>全选</span>
                            <input type="checkbox" @click="allPick(),checkModel()" v-model="checked">
                        </th>
                        <th>类型</th>
                        <th>商品名称</th>
                        <th>编号</th>
                        <th>商品单价</th>
                        <th>购买数量</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    <template v-for="(item1, index) in list">
                        <tr>
                            <tr v-for="(initem, inindex) in item1">                       
                                <td>
                                    <input type="checkbox" :value="initem.id" v-model="checkBoxModel" @click.stop="pickOne(index, inindex),checkPick()">
                                </td>
                                <td>{{ num(index) }}</td>
                                <td>{{ initem.id }}</td>
                                <td>{{ initem.name }}</td>
                                <td>{{ initem.price }}</td>
                                <td>
                                    <button @click="handleReduce(index, inindex)" :disable="initem.count === 1">-</button>
                                        {{ initem.count }}
                                    <button @click="handleAdd(index, inindex)">+</button>
                                </td>
                                <td>
                                    <button @click="handleRemove(index, inindex)">移除</button>
                                </td>
                            </tr>
                        </tr>
                    </template>
                </tbody>
            </table>
            <div>总价:¥{{ totalPrice }}</div>
        </template>
        <div v-else>购物车为空</div>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <script>
        var app = new Vue({
            el: '#app',
            data: {
                list: [
                    [{
                        id: 1,
                        name: 'iphone 7',
                        price: '6188',
                        count: 1,
                        isBuy: false,
                        cls: 'Eletronic Products'
                    }, {
                        id: 2,
                        name: 'ipad Pro',
                        price: '5888',
                        count: 1,
                        isBuy: false
                    }, {
                        id: 3,
                        name: 'macbook pro',
                        price: '21488',
                        count: 1,
                        isBuy: false
                    }],
                    [{
                        id: 4,
                        name: 'T-shirt',
                        price: '150',
                        count: 1,
                        isBuy: false,
                        cls: '生活用品'
                    }, {
                        id: 5,
                        name: 'cup',
                        price: '10',
                        count: 2,
                        isBuy: false
                    }, {
                        id: 6,
                        name: 'dish',
                        price: '30',
                        count: 1,
                        isBuy: false
                    }],
                    [{
                        id: 7,
                        name: 'apple',
                        price: '3',
                        count: 5,
                        isBuy: false,
                        cls: '农产品'
                    }, {
                        id: 8,
                        name: 'watermelon',
                        price: '15',
                        count: 1,
                        isBuy: false
                    }, {
                        id: 9,
                        name: 'cabbage',
                        price: '5',
                        count: 1,
                        isBuy: false
                    }]
                ],
                checkBoxModel: [],
                checked: false
            },
            computed: {
                totalPrice: function () {
                    var total = 0;           
                    for (var i = 0; i < this.list.length; i++) {
                        for (var j = 0; j < this.list[i].length; j++) {
                            var itemp = this.list[i][j];
                            if (itemp.isBuy) {
                                total += itemp.price * itemp.count;
                            }
                        }
                    }
                    return total.toString().replace(/\B(?=(\d{3})+$)/g, ',');
                }
            },
            methods: {
                handleReduce: function (index, inindex) {
                    if (this.list[index][inindex].count === 1) return;
                    this.list[index][inindex].count--;
                },
                handleAdd: function (index, inindex) {
                    this.list[index][inindex].count++;
                },
                handleRemove: function (index, inindex) {
                    this.list[index].splice(inindex, 1);
                },
                allPick: function () {
                    var _this = this;
                    if (_this.checked) {
                        _this.checkBoxModel = [];
                        _this.checked = false;
                    } else {
                        _this.checkBoxModel = [];
                        for (var i = 0; i < _this.list.length; i++) {
                            _this.list[i].forEach(function (item) {
                                _this.checkBoxModel.push(item.id);
                            });
                        }
                        _this.checked = true;
                    }
                },
                pickOne: function (index, inindex) {
                    if (this.list[index][inindex].isBuy) {
                        this.list[index][inindex].isBuy = false;
                    } else {
                        this.list[index][inindex].isBuy = true;
                    }
                },
                checkPick: function () {
                    _this = this;
                    var sumPic = 0;
                    var alength = 0;
                    for (var i = 0; i < _this.list.length; i++) {
                        for (var j = 0; j < _this.list[i].length; j++) {
                            if (_this.list[i][j].isBuy) {
                                sumPic++;
                            }
                        }
                        alength += _this.list[i].length
                    }
                    if (sumPic == alength) {
                        _this.checked = true;
                        console.log('all pick');
                    } else {
                        _this.checked = false;
                    }
                },
                num: function (index) {
                    for (var j = 0; j < this.list.length; j++) {
                        if (index === j) {
                            return this.list[j][0].cls;
                        }
                    }
                },
                checkModel: function () {
                    _this = this;
                    if (_this.checkBoxModel.length) {
                        newArr = _this.checkBoxModel.concat();
                        //console.log(newone);
                        for (var i = 0; i < _this.list.length; i++) {
                            for (var j = 0; j < _this.list[i].length; j++) {
                                var newone = newArr.shift();
                                if (_this.list[i][j].id === newone) {
                                    _this.list[i][j].isBuy = true;
                                }
                            }
                        }
                    } else {
                        for (var i = 0; i < _this.list.length; i++) {
                            for (var j = 0; j < _this.list[i].length; j++) {
                                _this.list[i][j].isBuy = false;
                            }
                        }
                    }
                }
            },
            created() {
                _this = this;
                _this.checkModel();
                console.log(_this.list[1][2].name);
            }
        });
    </script>
</body>
</html>

 

  • 0
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值