Vue之computed计算属性

demo.html

 1 <!DOCTYPE html>
 2 <html lang="en" xmlns:v-bind="http://www.w3.org/1999/xhtml" xmlns:v-html="http://www.w3.org/1999/xhtml"
 3       xmlns:v-on="http://www.w3.org/1999/xhtml">
 4 <head>
 5     <meta charset="UTF-8">
 6     <title>Vue Demo</title>
 7     <!--自选版本-->
 8     <!--<script src="https://cdn.jsdelivr.net/npm/vue@2.5.21/dist/vue.js"></script>-->
 9     <!-- 开发环境版本,包含了有帮助的命令行警告 -->
10     <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
11     <!-- 生产环境版本,优化了尺寸和速度 -->
12     <!--<script src="https://cdn.jsdelivr.net/npm/vue"></script>-->
13 </head>
14 <body>
15 <div id="app">
16     <div>
17         <h3>computed 计算属性举例</h3>
18         <div>
19             <p>
20                 method在使用时会执行所有方法;<br>
21                 computed在使用时只执行相关的操作;<br>
22                 computed属性比method更节省资源和性能;在需要复杂计算或耗时较多的操作时使用。<br>
23             </p>
24         </div>
25 
26         <hr>
27 
28         <div>
29             <h3>method方式实现</h3>
30             <button v-on:click="a++" type="button">
31                 ADD To A
32             </button>
33 
34             <button v-on:click="b++" type="button">
35                 ADD To B
36             </button>
37 
38             <p>A : {{a}}</p>
39             <p>B : {{b}}</p>
40             <p>Age + A = {{ageAddA()}}</p>
41             <p>Age + B = {{ageAddB()}}</p>
42         </div>
43 
44         <hr>
45 
46         <div>
47             <h3>computed 计算属性方式实现</h3>
48             <button v-on:click="c++" type="button">
49                 ADD To C
50             </button>
51 
52             <button v-on:click="d++" type="button">
53                 ADD To D
54             </button>
55 
56             <p>C : {{c}}</p>
57             <p>D : {{d}}</p>
58             <p>Age + C = {{ageAddC}}</p>
59             <p>Age + D = {{ageAddD}}</p>
60         </div>
61     </div>
62 
63 
64 </div>
65 <script src="app.js"></script>
66 
67 
68 </body>
69 </html>

 

app.js

 1 var app = new Vue({
 2     el: '#app',
 3     data: {
 4         a: 0,
 5         b: 0,
 6         age: 20,
 7         c: 0,
 8         d: 0,
 9 
10     },
11     methods: {
12         ageAddA: function () {
13             console.log("A:" + this.a);
14             return this.age + this.a;
15         },
16         ageAddB: function () {
17             console.log("B:" + this.b);
18             return this.age + this.b;
19         }
20     },
21 
22     computed:{
23         ageAddC: function () {
24             console.log("C:" + this.c);
25             return this.age + this.c;
26         },
27         ageAddD: function () {
28             console.log("D:" + this.d);
29             return this.age + this.d;
30         }
31     }
32 })

 

截图:

 

posted @ 2019-02-12 10:00  星瑞  阅读(564)  评论(0编辑  收藏  举报