vue.js計算屬性用法(computed)

_code小學生發表於2018-03-24
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <!-- Vue.js -->
    <script src="https://unpkg.com/vue/dist/vue.min.js"></script>
</head>
<body>
<div id="app">
    總價: {{ prices }}
</div>
</body>
</html>
<script>
    var app = new Vue({
        el:'#app',
        data:{
            package1:[
                {
                    name:'iphone7',
                    price:7199,
                    count:2
                },
                {
                    name:'ipad',
                    price:2888,
                    count:1
                }
            ],
            package2:[
                {
                    name:'apple',
                    price:3,
                    count:5
                },
                {
                    name:'banana',
                    price:2,
                    count:10
                }
            ]
        },
        //所有的計算屬性都以函式的形式寫在vue例項內的computed選項內,最終返回計算的結果
        computed:{
            prices:function () {
                var prices = 0;
                for (var i = 0;i<this.package1.length;i++){
                    prices += this.package1[i].price * this.package1[i].count;
                }
                for (var i = 0;i<this.package2.length;i++){
                    prices += this.package2[i].price * this.package2[i].count;
                }
                return prices;
            }
        }
    })
</script>

相關文章