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.
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>
Cannot access element shown by v-if in component mounted callback
原文:https://www.cnblogs.com/chucklu/p/14248027.html