vue学习二(计算属性computed和监听器watch)

1.1.computed  计算属性

先写注意事项把:computed和methods的区别
//computed定义的方法我们是以属性访问的形式调用的{{computedTest}}    computed是属性调用,computed带有缓存功能
//但是methods定义的方法,我们必须要加上{{computedTest()}} 来调用  ,methods是函数调用  而methods没有缓存功能
具体查看下面代码的区别
<span>总价格为{{sumPrice}}</span>

computed:{
                sumPrice(){
                    return this.xyjPrice*this.xyjNum+this.shzPrice*this.shzNum
                }
            }, 
<span>总价格为{{sumPrice()}}</span>
methods:{
                sumPrice(){
                    return this.xyjPrice*this.xyjNum+this.shzPrice*this.shzNum
                }
            },

2.1watch监听一个值的变化  做出相应的反应

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <meta name="viewport" content="width=device-width, initial-scale=1.0">
 6     <title>Document</title>
 7 </head>
 8 <body>
 9     <script src="../node_modules/vue/dist/vue.js"></script>
10 
11     <!--表单项自定义组件-->
12     <div id="app">
13        <!--某些结果式基于之前数据实时计算出来的  我们可以利用计算属性来完成-->
14        <ul>
15            <li>西游记 : 价格 {{xyjPrice}},数量:<input type="number" v-model="xyjNum"></li>{{msg}}
16            <li>水浒传 : 价格 {{shzPrice}},数量:<input type="number" v-model="shzNum"></li>
17             <span>总价格为{{sumPrice}}</span>
18        </ul>
19     </div>
20     <script>
21         
22         
23         
24 //computed定义的方法我们是以属性访问的形式调用的{{computedTest}}    computed是属性调用,computed带有缓存功能
25 //,但是methods定义的方法,我们必须要加上{{computedTest()}} 来调用  ,methods是函数调用  而methods没有缓存功能
26 
27         //computed 计算属性
28         //watch监听一个值的变化  做出相应的反应
29         let app = new Vue({
30             el:"#app",
31             data:{
32                 xyjPrice:88,
33                 shzPrice:89,
34                 xyjNum:3,
35                 shzNum:4,
36                 msg:""
37             },
38             computed:{
39                 sumPrice(){
40                     return this.xyjPrice*this.xyjNum+this.shzPrice*this.shzNum
41                 }
42             },
43             watch: {
44                 xyjNum:function(newValue,oldValue){
45                     alert("newValue="+newValue+",oldValue="+oldValue);
46                     if(newValue>=3){
47                         this.msg="库存超了";
48                         this.xyjNum = 3;
49                     }else{
50                         this.msg=""
51                     }
52                 }
53             },
54         })
55     </script>
56 </body>
57 </html>
View Code
原文地址:https://www.cnblogs.com/wanglli/p/13182723.html