computed,计算属性和methods看起来一样,不过区别还是挺大
一般在html的内容中,我们都使用mustache语法来赋值,在mustache中,一般也是直接写变量名,而函数的使用是需要加小括号的,不过计算属性却可以不加小括号,虽然也是函数,但是却是作为一个属性值,可以直接用变量名来调用
计算属性的优点
相比于函数methods,计算属性computed的优点为:
举例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
| <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <div id="app"> <h2>{{totalprice}}</h2> </div> <script src="../../../vue.js" charset="utf-8"></script> <script> const app = new Vue({ el: "#app", data: { user : [ {id:1, name:'lanzhan', age:22, money:100}, {id:2, name:'libai', age:21, money:100}, {id:3, name:'dufu', age:24, money:80} ] }, computed: { totalprice(){ let result = 0 for (let i=0;i<this.user.length;i++){ result += this.user[i].money } return result } } }) </script> </body> </html>
|