Vue - nextTick

Vue.js 推荐以“数据驱动”的方式思考,避免直接接触DOM。但是有时候会遇到这种情况:当在数据变化后,我们需要操作相应的DOM,如下面的例子:

<template>
    <div>
      <ul>
        <li v-for="(item,index) in message" :key="index" ref="list">{{item}}</li>
      </ul>
    </div>
</template>

<script>
export default{
    data(){
        return {
            message:[]
        }
    },
    mounted(){
        this.message = [1,2,3,4];
        console.log(this.$refs.list); //无dom元素输出为空
    }
}
</script>

这种情况该怎么处理呢?

  由于Vue 异步执行 DOM 更新:即数据变化之后,Vue 将开启一个队列,并缓冲在同一事件循环中发生的所有数据改变;从而你能看到页面这个时候已经显示数据了,但是操作dom的时候无输出,表明此时DOM还没有更新。如果想要在此时操作DOM的情况,可以使用一下两种方式:

1.setTimeout

  setTimeout(()=>{
    console.log(this.$refs.list);
  },20)
 
2.Vue.nextTick(callback)
  this.$nextTick(function(){
    console.log(this.$refs.list);
  })
 
以上两种方式都是在DOM更新完成后调用
 
了解更多原理,可参照:https://www.cnblogs.com/xujiazheng/p/6852124.html

猜你喜欢

转载自www.cnblogs.com/changxue/p/9134164.html