vue小作业:简易购物车

WTM随手一打就是标准的十五字

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>vue</title>
</head>

<body>
<div id="app">
  商品<input type="text" v-model="name">
  价格<input type="text" v-model="price">
  数量<input type="text" v-model="number">
  <button @click="GoodAdd">添加</button>
    <table>
        <thead>
            <tr>
                <th>序号</th>
                <th>商品</th>
                <th>单价</th>
                <th>数量</th>
                <th>合计</th>
                <th>操作</th>
            </tr>
        </thead>
        <tbody>
            <tr v-for = "(good,index) in goods">
                <td>{{index}}</td>
                <td>{{good.name}}</td>
                <td>{{good.price}}</td>
                <td><button @click="minus(index)" :disabled = "good.number===1" >-</button>{{good.number}}<button @click="add(index)">+</button></td>
                <td>{{good.price*good.number}}</td>
                <td><button @click="LineDel(index)">删除</button></td>
            </tr>
        </tbody>
    </table> 
    <p>总价:{{total}}</p>
</div>
 
<script type="text/javascript" src="https://cdn.staticfile.org/vue/2.2.2/vue.min.js"></script>
<script type="text/javascript">
    var app = new Vue({
        el:'#app',
        data:{
            goods:[],
            name:'',
            price:'',
            number:''
        },
        methods:{
            minus:function(index){
                this.goods[index].number--;
            },
            add:function(index){
                this.goods[index].number++;
            },
            GoodAdd(){
              var good={name:this.name,price:this.price,number:this.number}
              this.goods.push(good)
            },
            LineDel:function(index){
              this.goods.splice(index,1)
            }
        },
        computed:{
            total:function(){
                var arr = this.goods;
                var total = 0;
                for(var i = 0;i<arr.length;i++){
                    total += arr[i].price*arr[i].number;
                }
                return total;
            }
        }
    });
</script>
</body>
</html>
点赞

发表评论

电子邮件地址不会被公开。必填项已用 * 标注