第五章:利用计算属性写一个购物车案例

一、项目运行效果

第五章:利用计算属性写一个购物车案例

  • 1、点击增加与减少小计会变化
  • 2、商品前面复选框勾选后会计算总金额

二、具体代码

  • 1、html代码
<div id="app">
    <ul>
        <li v-for="good of goods">
            <input type="checkbox" @click="checkbox(good)" />
            <span>商品名称:{{good.goodname}}</span>
            <input type="button" value="-" @click="changeNum(0,good)" />
            <input type="number" v-bind:value="good.num || 0" />
            <input type="button" value="+" @click="changeNum(1,good)" />
            <span>单价:{{good.price}}</span>
            <span>小计:{{((good.num*good.price)?(good.num*good.price):0)|price}}</span>
        </li>
    </ul>
    <p>总金额:{{allPrice | price}}</p>
</div>
  • 2、js代码

var app = new Vue({
    el: '#app',
    data: {
        goods: [{
            'id': 0,
            'goodname': '肥皂',
            'price': 4.3
        }, {
            'id': 1,
            'goodname': '洗发水',
            'price': 34
        }, {
            'id': 2,
            'goodname': '洗衣粉',
            'price': 7.3
        }],
        goodnumber: null,
    },
    methods: {
        // 改变数量
        changeNum(arg1, item) {
            if (!item.num) {
                // $set是添加值
                this.$set(item, 'num', 0);
            }
            // 判断为真的时候为增加的方法,否则为假的方法
            if (arg1) {
                item.num++;
            } else {
                item.num--;
            }
        },
        // 设置选中与不选中
        checkbox(item) {
            if (item.active) {
                this.$set(item, 'active', false);
            } else {
                this.$set(item, 'active', true);
            }
            console.log(item);
        }
    },
    filters: {
        price(arg) {
            return arg.toFixed(2) + '元';
        }
    },
    computed: {
        // 计算总价
        allPrice() {
            var result = 0;
            for (var i in this.goods) {
                if (this.goods[i].active) {
                    result += this.goods[i].price * this.goods[i].num;
                }
            }
            return result;
        }
    }
})
上一篇:剑指 Offer 12. 矩阵中的路径


下一篇:Python操作Mysql数据库入门——数据导入pandas(数据分析准备)