天天看點

用Vue制作一個簡單購物車

先上一張效果圖:

用Vue制作一個簡單購物車

為什麼都用Vue開發網頁呢?因為它簡單便捷。

來給大家看一個Vue架構實作一個簡單的購物車,感受一下Vue的便捷。

構造主要還是老生常談的第三個部分:html,css,Javascript。

Html負責制作網頁上顯示購物車的表,并完成少部分邏輯(點選+商品數量加一;點選-商品數量減一;點選移除将商品數量置零)

Css負責渲染表的樣式

JS負責傳入資料并計算總價

上一下代碼:

<!DOCTYPE html>

<html en" xmlns:v-bind="http://www.w3.org/1999/xhtml" xmlns:v-on="http://www.w3.org/1999/xhtml">

<head>

    <meta charset="UTF-8">

    <title>ShoppingBag</title>

</head>

<!--配置CSS樣式-->

<style>

    table {

        border: 1px solid black;

    }

    table {

        width: 100%;

    }

    th {

        height: 50px;

    }

    th, td {

        border-bottom: 1px solid #ddd;

    }

</style>

<body>

<!--HTML部分-->

<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>

<div id="app">

    <table>

        <tr>

            <th>序号</th>

            <th>商品名稱</th>

            <th>商品價格</th>

            <th>購買數量</th>

            <th>操作</th>

        </tr>

        <tr v-for="huawei in Ip_Json">

            <td>{{ huawei.id }}</td>

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

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

            <td>

                <button v-bind:disabled="huawei.count === 0" v-on:click="huawei.count-=1">-</button>

                {{ huawei.count }}

                <button v-on:click="huawei.count+=1">+</button>

            </td>

            <td>

                <button v-on:click="huawei.count=0">移除</button>

            </td>

        </tr>

    </table>

    總價:${{totalPrice()}}

</div>

<!--JavaScript邏輯控制部分-->

<script>

    var app = new Vue({

        el: '#app',

        data: {

            Ip_Json: [{

                id: 1,

                name: 'huawei 10',

                price: 2600,

                count: 1

            },

                {

                    id: 2,

                    name: 'huawei P10',

                    price: 3999,

                    count: 1

                },

                {

                    id: 3,

                    name: 'huawei 12',

                    price: 4777,

                    count: 1

                }]

        },

        methods:{

            totalPrice : function(){

                var totalP = 0;

                for (var i = 0,len = this.Ip_Json.length;i<len;i++) {

                    totalP+=this.Ip_Json[i].price*this.Ip_Json[i].count;

                }

                return totalP;

            }

        }

    })

</script>

</body>

</html>

繼續閱讀