在什么时候用?
为什么在 Vue 生命周期的 created() 钩子函数进行的 DOM 操作一定要放在 Vue.nextTick() 的回调函数中?
原因是在 created() 钩子函数执行的时候 DOM 其实并未进行任何渲染,而此时进行 DOM 操作无异于徒劳,所以此处一定要将 DOM 操作的 js代码放进 Vue.nextTick() 的回调函数中。与之对应的就是 mounted 钩子函数,因为该钩子函数执行时所有的 DOM 挂载和渲染都已完成,此时在该钩子函数中进行任何 DOM 操作都不会有问题 。
在数据变化后要执行的某个操作,而这个操作需要使用随数据改变而改变的 DOM 结构的时候,这个操作都应该放进 Vue.nextTick() 的回调函数中。
学习 vue 有段时间了,但是对 vue 实例的生命周期还是有些许疑惑,在参考了一些网友的文章后,结合自己的理解,记录下帮助自己更好地学习。
实例生命周期钩子
生命周期图示,摘自官方:
各周期及其描述
data observer
) 和event/watcher
事件配置之前被调用。watch/event
事件回调。然而,挂载阶段还没开始,$el
属性目前不可见。render
函数首次被调用。el
被新创建的vm.$el
替换,并挂载到实例上去之后调用该钩子。(不会承诺所有的子组件也都一起被挂载。如果你希望等到整个视图都渲染完毕,可以用vm.$nextTick
替换掉mounted
)keep-alive
组件激活时调用。keep-alive
组件停用时调用。Vue
实例销毁后调用。调用后,Vue
实例指示的所有东西都会解绑定,所有的事件监听器会被移除,所有的子实例也会被销毁。对于执行时机和执行顺序,结合上面两项我们就能有个大概了解了。
结合实例深入理解
写一段代码,可以让我们的观察更直观些:
打印结果以及数据更新:
看一眼绿色方框围住的区域,在
beforeMount
时期,DOM 已经部分渲染了,这里就是应用了 虚拟DOM 的技术(Virtual DOM
),在Mounted
时期开始把数据渲染进去。实践笔记
一些关于实际应用中的东西:
beforeCreat
:可以做 loading 处理,让界面更友好created
:结束 loading 。发起后端请求,等待mounted
结束完成 DOM 渲染。其他一些操作mounted
:获取到DOM节点beforeDestroy
: 可以做一个确认停止事件的确认框nextTick
: 更新数据后立即操作 DOMVue.nextTick
描述: 在下次 DOM 更新循环结束之后执行延迟回调。在修改数据之后立即使用这个方法,获取更新后的 DOM。vue 官网
官方提供了一种写法,
vm.$nextTick
,用this
自动绑定到调用它的实例上参考