1. 程式人生 > >43.VUE學習之--元件之使用.sync修飾符與computed計算屬性超簡單的實現美團購物車原理

43.VUE學習之--元件之使用.sync修飾符與computed計算屬性超簡單的實現美團購物車原理

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <!--<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>-->
    <script type="text/javascript" src="../js/vue.js"></script>
</head>
<body>
<div id="hdcms">
    <!-- .sync 當資料改變時,會自動把子元件裡的值賦值到父元件goods裡,當goods的值改變時,totalPrice又會重新計算-->
    <hd-news :lists.sync="goods" ></hd-news>
    總計:{{totalPrice}}元
</div>
<script type="text/x-template" id="hdNews">
    <table border="1" width="90%">
        <tr>
            <th>商品名稱</th><th>商品價格</th><th>商品數量</th>
        </tr>
        <tr v-for="(v,k) in lists">
            <td>{{v.title}}</td><td>{{v.price}}</td>
            <td>
                <input type="text" v-model="v.num">
            </td>
        </tr>
    </table>
</script>
<script>
    var hdNews = {
        template: "#hdNews",
        props: ['lists']
    };
    new Vue({
        el: '#hdcms',
        components: {hdNews},
        //頁面載入完後,加自動執行
        computed:{
            totalPrice(){
                var sum=0;
                this.goods.forEach((v)=>{
                    sum+=v.num*v.price;
                })
                return sum;
            }
        },
        data: {
            goods:[
                {title:'iphone7Plus',price:100,num:1},
                {title:'後盾人會員',price:200,num:1},
            ]
        }
    });
</script>
</body>
</html>

效果: