watch对比computed

总结:

     computed和watch之间的区别:
            1.computed能完成的功能,Watch都可以实现
            2.watch能完成的功能,computed不一定能完成,比如:watch可以进行异步操作
        两个重要的小原则:
            1.所被vue管理的函数,最好写成普通函数,这样this指代的才是vm或组件实例对象
            2.所有不被vue所管理的函数(定时器的回调函数、ajax的回调函数、promise的回调函数)
              最好写成箭头函数,这样this的指向才是vm或组件实例对象。
1.姓名案例_computed实现
 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <meta http-equiv="X-UA-Compatible" content="IE=edge">
 6     <meta name="viewport" content="width=device-width, initial-scale=1.0">
 7     <title>姓名案例_计算属性</title>
 8     <!-- 引入vue -->
 9     <script type="text/javascript" src="../js/vue.js"></script>
10 </head>
11 <body>
12     <!-- 准备一个div容器 -->
13     <div id="root">
14         姓:<input type="text" v-model="firstName"><br/><br/>
15         名:<input type="text" v-model="lastName"><br/><br/>
16         全名:<span>{{fullName}}</span>
17     </div>
18 </body>
19 <script type="text/javascript">
20    Vue.config.productionTip = false //阻止vue在启动时生成生产提示。
21   const vm = new Vue({
22        el:'#root',
23        data:{
24            firstName:'',
25            lastName:''
26        },
27        computed:{
28                 /* 只读不改的简写,实际这里的函数相当于get */
29                 fullName(){
30                     console.log('get被调用了')
31                     return this.firstName + '-' + this.lastName
32                 }
33            }
34        
35    })
36 </script>
37 </html>

2.姓名案例_watch实现
 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <meta http-equiv="X-UA-Compatible" content="IE=edge">
 6     <meta name="viewport" content="width=device-width, initial-scale=1.0">
 7     <title>姓名案例_watch实现</title>
 8     <!-- 引入vue -->
 9     <script type="text/javascript" src="../js/vue.js"></script>
10 </head>
11 <body>
12     <!-- 准备一个div容器 -->
13     <div id="root">
14         姓:<input type="text" v-model="firstName"><br/><br/>
15         名:<input type="text" v-model="lastName"><br/><br/>
16         全名:<span>{{fullName}}</span>
17     </div>
18 </body>
19 
20 <script type="text/javascript">
21    Vue.config.productionTip = false //阻止vue在启动时生成生产提示。
22   const vm = new Vue({
23        el:'#root',
24        data:{
25            firstName:'',
26            lastName:'',
27            fullName:'张-三'
28        },
29         watch:{
30             firstName(newValue){
31                 this.fullName = newValue + '-' + this.lastName
32             },
33             lastName(newValue){
34                 this.fullName = this.firstName + '-' + newValue
35             }
36         }    
37    })
38 </script>
39 </html>

watch能完成异步操作,computed不能完成。

 

 
 

 

posted on 2021-10-28 19:10  我不想一直当菜鸟  阅读(62)  评论(0编辑  收藏  举报