Vue.js

购物车效果

2018-09-18  本文已影响0人  天赐很棒

body部分:

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <title>Document</title>

    <link rel="stylesheet" href="css/bootstrap.css">

</head>

<body>

    <div class="container">

        <table class="table table-bordered text-center">

            <thead>

                <tr>

                    <th class="text-center">编号</th>

                    <th class="text-center">名称</th>

                    <th class="text-center">单价</th>

                    <th class="text-center">数量</th>

                    <th class="text-center">总价</th>

                </tr>

            </thead>

            <tbody>

                <tr v-for='(value,index) in lhf'>

                    <td>{{index+1}}</td>

                    <td>{{value.name}}</td>

                    <td>{{value.price}}</td>

                    <td>

                    <button @click="lgy(index)">+</button>

                    <span>{{value.count}}</span>

                    <button @click="lbx(index)">-</button>

                    </td>

                    <td>{{value.count*value.price}}</td>

                </tr>

                <tr>

                    <td colspan="5" class="text-center">总计:{{total}}</td>

                </tr>

            </tbody>

        </table>

    </div>

js部分:

    <script src="js/vue.js"></script>

    <script>

        new Vue({

            el:'.container',

            data:{

                lhf:[

                    {name:'bannana',price:'3',count:'3',sub:'9'},

                    {name:'apple',price:'4',count:'4',sub:'16'},

                    {name:'pear',price:'5',count:'5',sub:'25'}

                ],

                total:0

            },

            methods:{

                lgy:function(index){

                this.lhf[index].count++,

                this.lhf[index].sub=(this.lhf[index].price*this.lhf[index].count).toFixed(2)

                this.getTotal()

            },

                lbx:function(index){

                if(this.lhf[index].count>1){

                this.lhf[index].count--,

                this.lhf[index].sub=(this.lhf[index].price*this.lhf[index].count).toFixed(2)

            }

                this.getTotal()

            },

            getTotal:function(){

                var len=this.lhf.length

                var sum= 0;

                for(var i=0;i<len;i++){

                    sum+=Number(this.lhf[i].sub)

                }

                this.total=sum.toFixed(2);

            }

        }

    })

    </script>

</body>

</html>

上一篇 下一篇

猜你喜欢

热点阅读