美文网首页
用vue做一个简单的购物车效果

用vue做一个简单的购物车效果

作者: greenPLUS | 来源:发表于2018-09-16 19:34 被阅读0次

简易购物车用到的指令有:
v-for=‘ ’:循环数组,对象,数组对象
v-on:click=‘ ’:用来绑定事件还可以用简写的 @事件名=‘函数名’

<div class='container'>
        <table class='table table-bordered text-center'>
            <thead>
                <tr>
                    <th>编号</th>
                    <th>品名</th>
                    <th>单价</th>
                    <th>数量</th>
                    <th>小计</th>
                </tr>
            </thead>
            <tbody>
                <tr v-for="(value,index) in list">
                    <td>{{index+1}}</td>
                    <td>{{value.pname}}</td>
                    <td>{{value.price}}</td>
                    <td>
                        <button @click='add(index)'>+</button>
                        <span>{{value.count}}</span> 
                         <button @click='redu(index)'>-</button>
                     </td>
                    <td>{{value.sub}}</td>
                </tr>
                <tr>
                    <td colspan="5">总价:¥{{sum}}</td>
                </tr>
            </tbody>
        </table>
    </div>

上边是vue指令写出超级简便省代码的框架

下边该是vue出场了!!

<script src='../js/vue.js'></script>
  <script type="text/javascript">
    new Vue({
        el:'.container',
        data:{
            list:[
                 {pname:'apple',price:3,count:2,sub:6},
                 {pname:'pear',price:4,count:3,sub:12},
                 {pname:'banana',price:5,count:4,sub:20}
            ],
            sum:0
        },
        methods:{
            add:function(ind){
                //数量
                this.list[ind].count++;
                //改变小计
                this.list[ind].sub=this.list[ind].count*this.list[ind].price;
                this.total();
            },
            redu:function(ind){
                //数量
                if(this.list[ind].count>1){
                   this.list[ind].count--;
                }
                //小计
                this.list[ind].sub=this.list[ind].count*this.list[ind].price;

                this.total();
            },
            total:function(){
                for(var i=0,tota=0;i<this.list.length;i++){
                        tota+=this.list[i].sub
                }
                this.sum=tota
            }
        }
    })
  </script>
QQ图片20180916193318.png

这是最后出来的效果

相关文章

网友评论

      本文标题:用vue做一个简单的购物车效果

      本文链接:https://www.haomeiwen.com/subject/hpufnftx.html