最近一直在学前端Vuejs,对于新手,很是整不明白Vuejs中的computed、methods、watch的区别。
其实官方文档给的还是很清楚的,但是对于新手,还是摸不透。
地址:https://cn.vuejs.org/v2/api/#computed
1#computed:计算属性将被混入到 Vue 实例中。所有 getter 和 setter 的 this 上下文自动地绑定为 Vue 实例。
2#methods:methods 将被混入到 Vue 实例中。可以直接通过 VM 实例访问这些方法,或者在指令表达式中使用。方法中的 this 自动绑定为 Vue 实例。
3#watch:是一种更通用的方式来观察和响应 Vue 实例上的数据变动。一个对象,键是需要观察的表达式,值是对应回调函数。值也可以是方法名,或者包含选项的对象。Vue 实例将会在实例化时调用 $watch(),遍历 watch 对象的每一个属性。
通俗来讲,
computed是在HTML DOM加载后马上执行的,如赋值;
而methods则必须要有一定的触发条件才能执行,如点击事件;
watch呢?它用于观察Vue实例上的数据变动。对应一个对象,键是观察表达式,值是对应回调。值也可以是方法名,或者是对象,包含选项。
所以他们的执行顺序为:默认加载的时候先computed再watch,不执行methods;等触发某一事件后,则是:先methods再watch。
下面的例子可以做为说明。
computed 属性 vs watched 属性:Vue 确实提供了一种更通用的方式来观察和响应 Vue 实例上的数据变动:watch 属性。当你有一些数据需要随着其它数据变动而变动时,你很容易滥用 watch——特别是如果你之前使用过 AngularJS。然而,通常更好的想法是使用 computed 属性而不是命令式的 watch 回调。
结合官方例子,自己做了一个demo,用户研究computed、methods、watch的区别。
先上代码块:
- <div id="app4">
- {{x}}---{{y}}---{{z}}--{{D}}
- <p>
- <button v-on:click="someMethod">Click</button>
- </p>
- <p>
- <input v-bind:value="DF"/>
- </p>
- </div>
- <script>
- var app4 = new Vue({
- el: '#app4',
- data: {
- x: 1,
- y: 2,
- z: 3,
- D: 99
- },
- watch: {
- /**
- * 类型: { [key: string]: string | Function | Object }
- * 一个对象,键是需要观察的表达式,值是对应回调函数。值也可以是方法名,或者包含选项的对象。Vue 实例将会在实例化时调用 $watch(),遍历 watch 对象的每一个属性。
- *
- */
- x: function (val, oldVal) {
- console.log('[watch]==>new: %s, old: %s', val, oldVal)
- },
- // 方法名
- y: 'someMethod',
- // 深度 watcher
- z: {
- handler: function (val, oldVal) {
- console.log('[watch]==>c===:'+val+','+oldVal)
- },
- deep: true
- }
- },
- methods: {
- /**
- * 类型: { [key: string]: Function }
- * methods 将被混入到 Vue 实例中。可以直接通过 VM 实例访问这些方法,或者在指令表达式中使用。方法中的 this 自动绑定为 Vue 实例。
- *
- */
- someMethod: function(){
- this.z = this.z + 999
- this.D = this.D + 10
- console.log('[methods]==>click someMethod for app4.y========>==================>')
- }
- },
- computed: {
- /**
- * 类型: { [key: string]: Function | { get: Function, set: Function } }
- * 计算属性将被混入到 Vue 实例中。所有 getter 和 setter 的 this 上下文自动地绑定为 Vue 实例。
- */
- DF: function(){
- return this.D
- },
- doubleDF: function(){
- return this.DF * 2
- },
- doDF: {
- get: function(){
- return this.D + 11
- },
- set: function(v){
- this.D = this.D - 11
- this.x = v - 222
- }
- }
- }
- })
- app4.x = 88 // -> new: -122, old: 1
- app4.z = 999 // -> 999,3
- app4.doDF //相当于get 此时这个值为:99+11
- console.log('[computed]==>相当于get 此时这个值为:99+11:'+app4.doDF)
- app4.doDF = 100 //相当于set 此时这个值为:100-11 x值为x-2
- console.log('[computed]==>相当于set 此时这个值为:100-11 x值为100-222:'+app4.doDF)
- console.log('[computed]==>再次打印D:'+app4.D)
- app4.doubleDF
- console.log('[computed]==>app4.doubleDF后的D:'+app4.doubleDF)
- </script>
Click
默认加载:
等点击按钮后,再看:(这里点了5次按钮)
以上为代码中执行的信息和顺序。
另外:在watch中,如果在函数块内给x赋值为:1000000,会出现什么情况???
我们运行一下,看看结果:
不管怎么执行,x的值始终都保持为:1000000,并且在默认加载的时候比之前多了一个watch执行信息。
原文链接:点击打开链接