vue는 비동기적으로 DOM을 업데이트 한다.
따라서 데이터 변경에 의해 DOM이 업데이트 될 경우, 바로 DOM에 접근할 수 없다.
<div v-if="showDiv" ref="target">hello</div>
...
data() {
return {
showDiv: false
}
},
async mounted() {
this.showDiv = true;
console.log(this.$refs.target); // 아직 DOM 업데이트X, 출력 안 됨
}
nextTick은 모든 데이터의 업데이트, 렌더링이 끝난 후 콜백함수를 실행해준다.
mounted() {
this.showDiv = true;
this.$nextTick(() => {
console.log(this.$refs.target); // target에 접근 가능
}
}