Subscribe on changes!

自定义指令mounted钩子执行时机与文档描述不一致

avatar
Dec 6th 2021

Version

3.2.24

Reproduction link

codepen.io

Steps to reproduce

1.请打开https://codepen.io/sakura-he/pen/VwMeMjd 2.请打开codepen内置控制台,观察自定义指令的钩子执行日志和父组件mounted钩子执行日志的顺序

What is expected?

与文档所描述的那样:自定义指令mounted:在绑定元素的父组件被挂载后调用 https://v3.cn.vuejs.org/guide/custom-directive.html#%E9%92%A9%E5%AD%90%E5%87%BD%E6%95%B0

What is actually happening?

自定义指令的mounted钩子中的代码先于父组件的生命周期mounted钩子执行

avatar
Dec 6th 2021

自定义指令mounted:在绑定元素的父组件被挂载后调用

父组件挂载后,并不是指父组件的 mounted 执行之后。这里是有区别的。

avatar
Dec 6th 2021

This could be also a documentation mismatch

avatar
Dec 6th 2021

image 兄弟,debugger一下发现好像没毛病的,父组件的mounted的console后执行好像是因为父组件mounted注册的钩子在自定义指令钩子后面,但确实是父组件先mounted再自定义指令mounted。可以用document.getElementsByClassName('xxx')获取dom来验证。

avatar
ycw
Dec 6th 2021

element hooks are emitted in 'depth-first' fashion, which is the same order as unmount. In addition, directive hooks always come after its bounding element hooks tightly. The docs is correct but a lil bit confusing as the 'after being mounted' (被挂载后) in description text should refer to moment, not the parent element hook. Here's a quick test:

元素钩子以“深度优先”的方式发出,与卸载的顺序相同。此外,指令钩子总是紧跟在它的边界元素钩子之后。文档是正确的,但有点令人困惑,因为描述文本中的“被挂载后”应该指的是时刻,而不是父元素钩子。这是一个快速测试:

sf.vuejs.org

avatar
Dec 7th 2021

谢谢大佬们的答疑,是我理解错了

avatar
Dec 7th 2021

经测试,在自定义指令的mounted钩子中可以获取到父组件的dom元素;可以证明钩子是在父组件挂在后执行的;