Vue系列教程-11-computed-计算属性

computed:计算属性,内部依然是方法,调用是不用加()相当于一个data。与methods的区别,调用多次,编译一次(如果值发生变化会自动重新编译),性能更好。

我是分割线


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <div id="app">
        {{ fullName }} <br>
        总价:{{ totalPrice }}
    </div>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <script>

        var app = new Vue({
            el: '#app',
            data: {
                message: 'Hello Vue!',
                firstName: '张',
                lastName: '三',
                books: [
                    {id: 1, name: '围城', price: 35},
                    {id: 2, name: '追风筝的人', price: 45},
                    {id: 3, name: '兄弟', price: 25},
                ]
            },
            // 计算属性,内部是方法,只是调用是不用加()
            computed: {
                fullName: function (){
                    return this.firstName + this.lastName;
                },
                totalPrice: function (){
                    let result = 0;
                    for (let book of this.books){
                        result += book.price;
                    }
                    return result;
                }

            }

        });
    </script>
</body>
</html>

我是分割线

Title
{{ fullName }}
总价:{{ totalPrice }}
点赞

发表评论