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

后端 未结 2 798
情歌与酒
情歌与酒 2021-02-07 18:39

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:50

    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.

    0 讨论(0)
  • 2021-02-07 19:07

    The lifecycle hooks around update respond to changes in the DOM. Watchers respond to changes in the data. DOM changes are generally in response to data changes, but they might not be data owned by the component in question. One example where updated could be used is noticing that slot content has updated.

    0 讨论(0)
提交回复
热议问题