最近再次复习了vue.js,一直混淆watch、computed、和methods三者。就谢谢笔记吧~
1.computed:
属性的结果会被缓存,除非依赖的响应式属性变化才会重新计算,主要当作属性来使用。
例:
1 2 3 4 5 6 7 8 9 10 11 |
computed:{ test1:function(){ return 'computed:test1'; }, test2(){ return 'computed:test2' } } //html引用 {{test1}} {{test2}} |
2.methods:
是一个方法,表示一个具体的操作,主要书写业务逻辑。
例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
methods:{ handleSubmit(){ this.count +=1 console.log('count:'+this.count) }, logInfo(event){ console.log(event); }, test(){ return 'methods:test'; } } <form v-on:submit.prevent="handleSubmit()"> <p>无pervent</p> <input type="submit" value="提交" /> </form> <input type="text" v-on:keyup.enter="logInfo($event)" /> <input type="text" @click.ctrl="logInfo($event)" /> {{test()}} |
数据量大,需要缓存的时候用computed;每次确实需要重新加载,不需要缓存时用methods
3.watch(侦听属性):
是一个对象,键是需要观察的表达式,值是对应回调函数,主要用来监听某些特定数据的变化,从而进行某些具体的业务逻辑操作;可以看做是computed和methods 的结合体。
例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
let app11 = new Vue({ el: '#app-11', data: { firstName: 'Foo', lastName: 'Bar', fullName: '1' }, watch: { firstName: function(val) { this.fullName = val + ' ' + this.lastName }, lastName: function(val) { this.fullName = this.firstName + ' ' + val }, firstName: function(newValue,oldValue){ console.log(newValue+' '+oldValue) //console.log('changed firstName') } } }); <div id="app-11"> {{ firstName }} <input type="text" v-model="firstName"/> </div> |
-->http://www.imooc.com/article/49239?block_id=tuijian_wz 不错的总结吧~