What is the difference between updated hook and watchers in VueJS?

后端 未结 2 1156
予麋鹿
予麋鹿 2021-02-07 18:18

I\'m discovering VueJS and I don\'t understand exactly the differences between updated and watchers.

Updated hook

It is a lifecycle hook. Accordin

2条回答
  •  失恋的感觉
    2021-02-07 18:53

    I think a better analogous lifecycle hook to the watchers may be the beforeUpdate hook. The updated hook is called after the virtual DOM has re-rendered, whereas beforeUpdate is called before the virtual DOM has re-rendered. You can see a visual representation of this on the diagram you linked to.


    in which cases would it be best to use updated instead of watchers ? (...) I can't figure out what are the pros of updating whenever a data changes (updated) if we can be more accurate (watch).

    The documentation says that you should prefer a watcher or computed property instead of updated if it is possible to achieve your goal that way. My understanding is that the updated hook was included to allow users to watch for any changes to the virtual DOM (see below).


    Here's the explanation from the Vue 2.0 release notes on watch vs. updated:

    User watchers created via vm.$watch are now fired before the associated component re-renders. This gives the user a chance to further update other state before the component re-render, thus avoiding unnecessary updates. For example, you can watch a component prop and update the component's own data when the prop changes.

    To do something with the DOM after component updates, just use the updated lifecycle hook.

提交回复
热议问题