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 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
| <!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>Vue计算属性/侦听器/方法比较</title> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script> </head> <body> <div id="app"> <h1>计算属性:computed</h1> {{fullName}} <h1>方法:methods</h1> {{fullName2()}} <h1>侦听器:watch</h1> {{watchFullName}} <h1>年龄</h1> {{age}} </div> <script> var other = 'This is other'; var app = new Vue({ el:"#app", data:{ firstName:"zhang", lastName:"san", watchFullName:"zhangsan", age:18, }, watch: { firstName:function(newFirstName, oldFirstName){ console.log("firstName触发了watch,newFirstName="+newFirstName+",oldFirstName="+oldFirstName) this.watchFullName = this.firstName+this.lastName+","+other }, lastName:function(newLastName, oldLastName){ console.log("lastName触发了watch,newLastName="+newLastName+",oldLastName="+oldLastName) this.watchFullName = this.firstName+this.lastName+","+other } }, computed: { fullName:function(){ console.log("调用了fullName,计算了一次属性") return this.firstName+this.lastName+","+other; } }, methods: { fullName2:function(){ console.log("调用了fullName,执行了一次方法") fullName2 = this.firstName+this.lastName+","+other; return fullName2; } } }); </script> </body> </html>
|