sun-10387834

一、computed的本质?

computed为什么不像methods一样加小括号使用?

正常使用computed方式

运行结果

 

 至于为什么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的本质写法

运行结果

 

 

 

二、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>
computed存在缓存机制验证

运行结果

 

 运行结果说明:methods调用几次则方法执行几次,而computed只执行一次。因此推断computed存在缓存机制。

相关文章: