005 Vue 计算属性

计算属性 computed

                data中的数据可以直接在html中通过差值表达式直接引用,但是有时候,我们想要data中的数据经过转换或者简单的计算再展示

            【注意】computed中定义的函数而非变量

1. 简单使用

                computed:{

                       fullName(){

                           return this.lastName + " " + this.firstName;

                       }

                   }

2. 复杂使用

                当计算比较复杂时,就显示出计算属性的优势了

                new Vue({

                    el: "#app",

                    data:{

                        firstName: "Blog",

                        lastName: "Carrey",

                        books:[

                            {id:001, name: '计算机原理', price: 120},

                            {id:002, name: '计算方法论', price: 123},

                            {id:003, name: '人机工程学', price: 201},

                            {id:004, name: '最优化理论', price: 223},

                        ],

                    },

                    computed:{

                        fullName(){

                            return this.lastName + " " + this.firstName;

                        },

                        totalPrice(){

                            var TP = 0;

                            for(var book of this.books){

                                TP += book.price;

                            }

                            return TP;

                        }

                    }

                })

3. 每一computed对象的元素都有一个set变量和get变量,即完整的computed属性应写成:

                    fullName:{

                        set:function(newValue){

                            var res = newValue.split(" ");

                            this.firstName = res[0];

                            this.lastName = res[1];

                        },

                        get: function(){

                            return this.lastName + " " + this.firstName;

                        }

                    },

                其中,调用属性fullName时,调用的是get函数,给属性fullName赋值时,调用的是set函数

           

4. 可以看到,computed中定义的是函数,这和methods是一样的,那为什么还多此一举来一个computed呢

                因为函数每次被调用时,都会重新执行一遍

                而计算属性会进行缓存,如果多次使用,计算属性只会计算一次

原文地址:https://www.cnblogs.com/carreyBlog/p/13667749.html