一、computed的本質?
computed為什么不像methods一樣加小括號使用?

1 <!DOCTYPE html> 2 <html lang="en"> 3 4 <head> 5 <meta charset="UTF-8"> 6 <meta name="viewport" content="width=device-width, initial-scale=1.0"> 7 <title>Document</title> 8 </head> 9 10 <body> 11 <div id='div1'> 12 <h2>{{hobbyList}}</h2> 13 </div> 14 </body> 15 <script src='../js/vue.js'></script> 16 <script> 17 const app = new Vue({ 18 el: '#div1', 19 data: { 20 message: 'hello vue!' 21 }, 22 computed: { 23 hobbyList() { 24 return ['baseball', 'football', 'pingpang', 'basketball'] 25 } 26 }, 27 }); 28 </script> 29 30 </html>
運行結果
至於為什么computed為什么不像methods一樣使用小括號調用,是由於computed本身就是一個屬性,其本質是computed內部有兩個方法(set和get),computed最終的道德的結果是get方法的返回值,而set方法很少使用到,因此簡化寫法就是上述正常使用computed的格式,其本質寫法如下展示。

1 <!DOCTYPE html> 2 <html lang="en"> 3 4 <head> 5 <meta charset="UTF-8"> 6 <title>Title</title> 7 </head> 8 9 <body> 10 <div id="div1"> 11 <h2>{{hobbyList}}</h2> 12 </div> 13 </body> 14 <script src="../js/vue.js"></script> 15 <script> 16 const app = new Vue({ 17 el: '#div1', 18 data: { 19 message: "hello vue!" 20 }, 21 computed: { 22 hobbyList: { 23 set: function() { 24 25 }, 26 get: function() { 27 return ['baseball', 'football', 'pingpang', 'basketball'] 28 } 29 } 30 }, 31 }); 32 </script> 33 34 35 </html>
運行結果
二、computed和methods的區別?
1、methods使用時,一般情況需要加括號,而computed則不需要。
2、methods每次調用時會重新執行函數,而computed在其內部變量不變或其返回值不變的情況下多次調用只會執行一次,后續執行時直接從緩存中獲取該computed的結果。

1 <!DOCTYPE html> 2 <html lang="en"> 3 4 <head> 5 <meta charset="UTF-8"> 6 <title>Title</title> 7 </head> 8 9 <body> 10 <div id="div1"> 11 <p>{{getName()}}</p> 12 <p>{{getName()}}</p> 13 <p>{{getName()}}</p> 14 <p>{{getName()}}</p> 15 16 <p>{{name}}</p> 17 <p>{{name}}</p> 18 <p>{{name}}</p> 19 <p>{{name}}</p> 20 </div> 21 </body> 22 <script src="../js/vue.js"></script> 23 <script> 24 const app = new Vue({ 25 el: '#div1', 26 data: { 27 message: "hello vue!" 28 }, 29 methods: { 30 getName() { 31 console.log("methods方法被調用了") 32 return "kelvin" 33 } 34 }, 35 computed: { 36 name() { 37 console.log("computed計算屬性被調用了"); 38 return "mary" 39 } 40 }, 41 }); 42 </script> 43 44 45 </html>
運行結果
運行結果說明:methods調用幾次則方法執行幾次,而computed只執行一次。因此推斷computed存在緩存機制。