VueJs, difference between computed property and watcher?

前端 未结 6 1077
孤街浪徒
孤街浪徒 2020-12-09 01:24

On Vue.js documentation there is an example like below:

var vm = new Vue({
  el: \'#demo\',
  data: {
    firstName: \'Foo\',
    lastName: \'Bar\',
    full         


        
6条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-09 02:08

    Computed properties have a a very specific purpose: composing new data derived from other data. They are used whenever you have some data and need to transform it, filter it, or otherwise manipulate it before using it in the template.

    Computed properties always have to return a value, should not have any side effects, and they have to be synchronous.

    So there are quite some situations where computed properties won't help you, for example: your component receives a prop, and whenever the prop changes, your component had to make an ajax request. For this, you would need a watcher.

    Watchers are not useful as often as computed properties, so you should always think about whether or not a computed property can solve your problem, and only fall back on a watcher (or sometimes a method) if that is not the case.

提交回复
热议问题