Some directives can only work on elements that are already in the DOM, such as autofocus:
Vue.directive('autofocus', {
bind() {
Vue.nextTick(() => this.el.focus())
}
});
However, the page component is compiled right away but it's only inserted into the DOM when it's mounted after the data and activate hooks are done. This results in nextTick running before the element is in the DOM, resulting in the element never getting focus.
Since nextTick obviously doesn't ensure that the element is in the DOM, what can be used instead?
nextTick is intended to be used right after you modified some reactive data.
For your use case, it seems more appropriate to do this:
bind () {
this.vm.$once('hook:attached', () => this.el.focus())
}
Most helpful comment
nextTickis intended to be used right after you modified some reactive data.For your use case, it seems more appropriate to do this: