nextTick

87 阅读1分钟

nextTick

nextTick在下次 DOM 更新循环结束之后执行延迟回调。在修改数据之后立即使用这个方法,获取更新后的 DOM

<template> 
  <div>{{ name }}</div> 
</template>

<script> 
export default { 
  data() { 
    return { 
      name: "" 
    } 
  }, 
  mounted() { 
    console.log(this.$el.clientHeight) // 0 
    this.name = "better" 
    console.log(this.$el.clientHeight) // 0 
    this.$nextTick(() => { 
      console.log(this.$el.clientHeight) // 18 
    }); 
  } 
}; 
</script>

此时发现直接获取最新的DOM相关的信息是拿不到的,只有在nextTick中才可以获取到最新的DOM信息

nextTick还可以作为一个promise使用

Vue.nextTick()
  .then(function(){
    // DOM 更新了
  })