vue--$nextTick()使用

本文深入探讨Vue.js中异步更新队列的工作原理,解释为何数据变化后不会立即更新DOM,以及如何利用Vue的$nextTick方法确保DOM更新后的回调执行。同时,通过实例分析ElementUI分页组件在特定浏览器下的DOM更新问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

html:

<div id="div" v-if="showDiv">这是一段文本</div>

<button @click="getText">获取div内容</button>

js:

data: {

showDiv: false

},

methods: {

getText: function() {

        this.showDiv = true;

会抛出一个错误: cannot read property 'innerHTML' of null;这里涉及到一个重要的概念: 异步更新队列

Vue在观察到数据变化时并不是直接更新DOM,而是开启一个队列,并缓冲在同一事件循环中发生的所有数据改变。在缓冲时会去除重复数据,从而避免不必要的计算和DOM操作。然后,在下一个事件循环tick中,Vue刷新队列并执行实际工作。

     //直接取报错,还没有创建div,如果不是v-if v-show的话,不报错

   //   var text = document.getElementById('div').innerHTML;

      //    console.log(text);

   // 等待dom更新完成后执行回调 

     this.$nextTick(function() {

          var text = document.getElementById('div').innerHTML;

          console.log(text);

     });

}

}

实际使用遇到的bug:

elemntUI的分页在ie下跳转至——页 ,前端分页时 只能执行一次,后面修改页数 不更行dom

<el-pagination @size-change="handleSizeChange" @current-change="currentChange" :current-page="page" :page-size="1" layout="prev, pager, next, jumper" :total="total"  :key="timeStrap"> </el-pagination>

 

return{

page:1,

timeStrap:'',

}

methods:{

currentChange(currentPage){

   this.page=currentPage;

  this.$nextTick(()=>{this.timeStrap=new Date().getTime();})

}

outterTabClick(tab){

}

   this.page=1;

   this.$emit('update:activeName',tab.name)

},

innerTabClick(){

}

 this.page=1;

}

},

computed:{

   index(){ return this.page-1;},

activeNameModel:{

       get(){

    return  this.activeName;

    },

   set(val){//子组件传父组件语法糖update

     this.$emit('update:activeName',val)

    }

  },

 distrustIncItem(){

    if(this.distrustIncList){

      return this.distrustIncList.length?(this.distrustIncList[this.index]?this.disrusIncList[this.index]:{}):{};

     }

  return {};

  },

total(){

 if(this.activeName==='first'){return this.distrustIncList.length?this.distruIncList.length:0;}else if(this.activeName==='second'){

      if(this.activeHireName==='hirerJudgeDocs'){return this.hirerJudgeDocsListCount;}else         if(this.activeHireName=='hirerSessionDocs'){return this.hirerSessionDocsListCount;}else if(this.activeName==='third'){

       if(this.activeOtherName==='judgeDocs'){return  this.judgeDocsListCount;}else if(this.activeOtherName==='executedInc'){

       return  this.extcutedIncListCount;

     }else if(this.activeOtherName==='sessionDocs')){return  this.sessionDocs'ListCount;}else if(this.activeOtherName==='noti ceDocs')){return  this.noticeDocsListCount;}

}

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值