Vue實戰之建立購物車

Vue實戰之建立購物車

1.效果演示:

cart.gif

2.相關代碼:

index.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>購物車示例</title>
    <link rel="stylesheet" type="text/css" href="../css/style.css">
</head>
<body>

<div id="app" v-cloak>
    <template v-if="list.length">
        <table border="1px" style="border-collapse:collapse;">
            <thead>
            <tr>
                <th></th>
                <th>商品名稱</th>
                <th>商品單價</th>
                <th>購買數量</th>
                <th>操作</th>
            </tr>
            </thead>
            <tbody>
            <tr v-for="(item,index) in list">
                <td>{{index+1}}</td>
                <td>{{item.name}}</td>
                <td>{{item.price}}</td>
                <td>
                    <button @click="handleReduce(index)"
                            :disabled="item.count ===1"
                    >-
                    </button>
                    {{item.count}}
                    <button @click="handleAdd(index)">+</button>
                </td>
                <td>
                    <button @click="handdleRemove(index)">移除</button>
                </td>
            </tr>
            </tbody>
        </table>
        <div>總價:&yen;{{totalPrice}}</div>
    </template>
    <div v-else>購物車爲空</div>
</div>


<script src="../js/vue.js"></script>
<script src="../js/index.js"></script>
</body>
</html>

index.js:

/**
 * Created by Administrator on 2018/10/17 0017.
 */

var app = new Vue({

    el: "#app",
    data: {
        list: [
            {
                id: 1,
                name: 'iPhone7',
                price: 6188,
                count: 1
            },
            {
                id: 2,
                name: 'iPad Pro',
                price: 5888,
                count: 1
            },
            {
                id: 3,
                name: 'MacBook Pro',
                price: 21488,
                count: 1
            }
        ]
    },
    computed: {
        totalPrice:function () {
            var total = 0;
            for (var i=0;i<this.list.length;i++){
                var item = this.list[i];
                total += item.price*item.count;
            }
            return total.toString().replace(
                /\B(?=(\d{3})+$)/g,","
            );
        }
    },
    methods: {
        handleReduce:function (index) {
            if(this.list[index].count===1){
                return;
            }
            this.list[index].count --;
            
        },
        handleAdd:function (index) {
            this.list[index].count ++;

        },
        handdleRemove:function (index) {
            this.list.splice(index,1);
        }

    }
});

style.css:

[v-cloak]{
    display: none;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章