Cannot access element shown by v-if in component mounted callback
Vue renders to the DOM asynchronously. So, even though you are setting your loaded property to true
, the ref
will not exist until the next tick in Vue's cycle.
To handle that, use the $nextTick
method.
vuejs mounted is called even if component was not loaded via v-if
console.clear() new Vue({ el: "#app", data:{ loading: true }, mounted(){ setTimeout(()=> { this.loading = false this.$nextTick(() => console.log(this.$refs.done)) }, 1000) } })
<script src="https://unpkg.com/vue@2.4.2"></script> <div id="app"> <div v-if="loading">Loading</div> <div ref="done" v-else>Done</div> </div>