image.png

代码

<!DOCTYPE html>
<html lang="zh-cn">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Vue.js 监听属性-简单的购物车</title>
    <script src="//static.gzj2001.com/vue/vue.js"></script>
    <style>
        table {
            border: 1px soild black;
            width: 100%;
        }

        th {
            height: 50px;
        }

        th,
        td {
            border: 1px solid #ddd;
        }
    </style>
</head>

<body>
    <div id="app">
        <table>
            <tr>
                <th>序号</th>
                <th>商品名称</th>
                <th>商品价格</th>
                <th>商品数量</th>
                <th>操作</th>
            </tr>
            <tr v-for="pro in phones">
                <td>{{pro.id}}</td>
                <td>{{pro.name}}</td>
                <td>{{pro.price}}</td>
                <td>
                    <button v-on:click="pro.number=pro.number+1">+</button>
                    {{pro.number}}
                    <button v-on:click="pro.number=pro.number-1">-</button>
                </td>
                <td>
                    <button v-on:click="pro.number=0">删除</button>
                </td>
            </tr>
        </table>
        <div>总价:{{total()}}</div>
    </div>
    <script>
        new Vue({
            el: "#app",
            data: {
                phones: [
                    {
                        id: 1,
                        name: "iphone6",
                        price: 5000,
                        number: 1
                    },
                    {
                        id: 2,
                        name: "iphone7",
                        price: 6000,
                        number: 1
                    },
                    {
                        id: 3,
                        name: "iphone8",
                        price: 7000,
                        number: 1
                    }]


            },methods:{
                total:function(){
                    let price = 0 ;
                    for(let x = 0 , len = this.phones.length;x<len;x++){
                        price = price + this.phones[x].price * this.phones[x].number;
                    }
                    return price;
                }
            }
        })
    </script>
</body>

</html>

效果

image.png