zoukankan      html  css  js  c++  java
  • 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呢

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

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

  • 相关阅读:
    关于异步IO与同步IO的写操作区别
    慢慢开始记录一些技术心得吧
    写了placement new就要写placement delete
    关于针对class自定义new操作符失败的函数处理
    operator->和operator->*
    关于继承中的拷贝构造函数
    关于g++编译模板类的问题
    关于互斥锁,条件变量的内核源码解析
    关于sigwait
    观察者设计模式
  • 原文地址:https://www.cnblogs.com/carreyBlog/p/13667749.html
Copyright © 2011-2022 走看看