Vue.nextTick
作用
在 DOM 更新后,执行一个回调。
// DOM 还没有更新
Vue.nextTick(function () {
// DOM 更新了
})
Vue 何时更新 DOM
Vue 在修改数据后,DOM 不会立刻更新,而是等同一事件循环中的所有数据变化完成之后,再统一进行 DOM 更新。
应用场景
created/mounted 操作 DOM
mounted: function () {
this.$nextTick(function () {
// Code that will run only after the
// entire view has been rendered
})
}
显示输入框并获取焦点
showInput() {
this.show = true
this.$nextTick(function () {
// DOM 更新了
document.getElementById("keywords").focus()
})
}