computed属性和watch属性的区别之四【购物车之computed】

来源:互联网 发布:淘宝top api易语言sdk 编辑:程序博客网 时间:2024/06/07 10:55
<body>    <div id = 'app'>        <div>            <h3>{{title}}</h3>        </div>        <div>            <div>                <table>                    <thead>                        <tr>                            <td>名称</td>                            <td>价格(元)</td>                            <td>数量(kg)</td>                            <td>共计(元)</td>                        </tr>                    </thead>                    <tbody>                        <tr v-for = 'item in list '>                            <td>{{item.name}}</td>                            <td><input type="number" v-model = 'item.price'></td>                            <td><input type="number" v-model = 'item.number'></td>                            <td>{{item.price * item.number}}</td>                        </tr>                        <tr>                            <td>合计</td>                            <td>{{single_price_sum}}</td>                            <td>{{single_number_sum}}</td>                            <td>{{all_total}}</td>                        </tr>                    </tbody>                </table>            </div>        </div>    </div>    <script src="https://cdn.bootcss.com/vue/2.5.8/vue.min.js"></script>    <script type="text/javascript">        var _vm = new Vue({            data : {                title : 'computed属性和watch属性的区别之四【购物车之computed】',                list : [                    {id : 1, name : '大白菜', price : 10, number : 1, },                    {id : 2, name : '小白菜', price : 20, number : 2,},                    {id : 3, name : '中白菜', price : 30, number : 3,}                ]            },            computed : {                all_total : function() {                    var _total = 0 ;                    this.m_each(function(item) {                        _total += item.price * item.number ;                    }) ;                    return _total ;                },                single_number_sum : function() {                    var _num = 0 ;                    this.m_each(function(item) {                        _num += parseFloat(item.number) ;                    }) ;                    return _num ;                },                single_price_sum : function() {                    var _price = 0 ;                    this.m_each(function(item) {                        _price += parseFloat(item.price) ;                    }) ;                    return _price ;                }            },            methods : {                m_each : function(callback) {                    for(var i = 0; i < this.list.length; i++) {                        callback(this.list[i]) ;                    }                }            }        }).$mount('#app') ;    </script></body>