Vue中computed和watch比较
Vue在监听数据的时候我们都会用computed和watch,但是很少人真正的去比较两个的区别,一般都是能实现就行。本人也是,习惯了watch,之后就几乎没用过computed。所以用官网的例子理解一下这两者的区别。
computed: { // 计算属性的getter reversedMessage: function () { console.log('调用了'); return this.message.split('').reverse().join(''); } },
默认是getter方法,在页面中直接使用{{reversedMessage}}。官网上说用methods也能实现相同的功能。
methods: { reversedMessage: function () { console.log('调用了'); returnthis.message.split('').reverse().join(''); } }
页面使用{{reversedMessage()}}
然而不同的地方就在于计算属性computed有缓存。当我们连续调用计算属性:
console.log(vm.reversedMessage) console.log(vm.reversedMessage) console.log(vm.reversedMessage)
你会发现计算属性是基于它们的依赖进行缓存的。只在相关依赖发生改变时它们才会重新求值。这就意味着只要 message 还没有发生改变,多次访问 reversedMessage 计算属性会立即返回之前的计算结果,而不必再次执行函数。
Methods就不同,你要是多次调用:
{{reversedMessage()}} {{reversedMessage()}} {{reversedMessage()}}
那么这个方法就会执行多次。
至于为什么需要缓存,在计算性能开销较大的时候,在依赖不变的时候就不用执行方法。
watch也是监听属性,跟computed一样也是依赖的改变了就会改变,不同的是,当你一个数据关联两个数据的时候,watch两个数据还不如直接一个computed。
firstName: 'Foo', lastName: 'Bar', fullName: 'Foo Bar'
fullName依赖于firstName和lastName,如果我们要用watch,那么就要监听两个数据
watch: { firstName: function (val) { this.fullName = val + ' ' +this.lastName }, lastName: function (val) { this.fullName = this.firstName + '' + val } }
使用计算属性computed:
fullName: function () { return this.firstName + ' ' +this.lastName }
这就是watch和computed在选择使用的时候要考虑的一个重要因素,另外一个重要因素是官网所说的当需要在数据变化时执行异步或开销较大的操作时,watch方式是最有用的。简单来说就是涉及异步操作然后需要设定不同中间值等,这时候就使用watch。
Computed还有一个setter方法:
fullName: { // getter get: function () { console.log('get'); return this.firstName + ' ' +this.lastName; }, // setter set: function (newValue) { this.firstName = '120'; this.lastName = '021'; console.log('set'); } }
然后我们调用:
vm.fullName = ‘John Doe’;
你会发现,首先触发set方法,然后执行get方法,得到的结果是120 021,这就表明我们需要验证一些数据然后要根据验证得到不同的结果的时候我们就可以使用set进行逻辑验证然后设置对应的结果,最后通过get方法得到最终的结果。
欢迎关注Coding个人笔记 公众号
- Vue中computed,methods,watch用法上的异同
- Vue.js计算属性computed与watch(5)
- Vue的watch和computed方法的使用及区别介绍
- vue中watch和computed的区别?
- Vue中computed VS watch 区别 及computed VS method区别
- vue中的computed和watch不同
- 前端进阶:vue中的computed和watch的异同
- Vue实例三个对象(methods,computed,watch)的差别
- VUE之watch与computed
- Vue计算属性computed:{}和侦听器watch:{}
- Vue.js中computed、methods、watch的使用
- vue中watch和computed属性作用及区别
- Vue中的methods、watch、computed的区别
- vue中computed & methods & watch 的区别
- Vue的计算属性computed、方法methods、侦听器watch的区别
- Vue中watch和computed的使用演示
- vue.js中的computed和methods和watch之间的区别
- vue 计算属性computed和观察watch 和方法methods
- vue生命周期、computed属性和 method方法、watch 属性区别
- vue.js重学之旅(2)——vue.js里的数据操作(data,methods,computed,watch)