Vue 'updated' 生命周期钩子
示例
使用 updated
生命周期钩子,在每次 DOM 树更新时向控制台写入一条消息。
export default {
data() {
return {
sliderVal: 50,
renderCount: 0
}
},
updated() {
this.renderCount++;
console.log('Updated ' + this.renderCount + ' times.')
}
}
运行示例 »
定义和用法
updated
生命周期钩子发生在 DOM 树更新之后。
如果在 updated
钩子中修改了某个属性或执行了其他会触发新渲染的操作,那么在新的渲染之后 updated
钩子将再次被调用,这很可能会创建一个无限循环。
为了避免无限循环,我们应该始终考虑使用 beforeUpdate
生命周期钩子,而不是 updated
生命周期钩子。
this.$nextTick()
或 nextTick()
函数也可以用来在 DOM 更新后运行代码。
注意:在上面的示例中,我们将渲染计数写入控制台,因为修改视图会重新激活 updated
钩子并导致无限循环。
相关页面
Vue 教程:Vue 生命周期钩子
Vue 教程: 'beforeUpdate' 钩子
Vue 参考:Vue 'beforeUpdate' 生命周期钩子
Vue 参考:Vue $nextTick() 方法