计算属性、方法和侦听器

    技术2022-07-14  71

    计算属性

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>计算属性、方法和侦听器</title> <script src="./vue.js"></script> </head> <body> <div id="root"> {{fullName}} </div> <script> var app = new Vue({ el: '#root', data: { firstname: "hello", secendname: "world" }, //计算属性 computed: { fullName: function () { return this.firstname + " " + this.secendname } } }) </script> </body> </html>

    计算属性在使用的时候会有一个缓存,其依赖的data,在没有发生变化的时候,计算属性就不会在进行调用了,会相对的提高了性能

    方法

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>计算属性、方法和侦听器</title> <script src="./vue.js"></script> </head> <body> <div id="root"> {{fullName()}} </div> <script> var app = new Vue({ el: '#root', data: { firstname: "hello", secendname: "world" }, methods:{ fullName: function() { return this.firstname + " " + this.secendname } } }) </script> </body> </html>

    方法使用没有计算属性效率高,因为每次不相干的数据被修改,方法属性还是会调用相关的函数

    侦听器

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>计算属性、方法和侦听器</title> <script src="./vue.js"></script> </head> <body> <div id="root"> {{fullName}} </div> <script> var app = new Vue({ el: '#root', data: { firstname: "hello", secendname: "world", fullName:"hello world" }, watch:{ firstname: function(){ this.fullName = this.firstname + " " + this.secendname }, secendname: function(){ this.fullName = this.firstname + " " + this.secendname } } }) </script> </body> </html>

    相比于计算属性,虽然侦听器也可以缓存数据,但是写法冗余

    总结

    如果实现一个功能3种方法都可以实现,选择上面 计算属性>>侦听器>>方法

    Processed: 0.033, SQL: 9