美文网首页
vue基础--this.$nextTick(function()

vue基础--this.$nextTick(function()

作者: 柒个M | 来源:发表于2020-08-31 13:46 被阅读0次

今天在浏览别人的代码时,发现之前一直含糊的语法,this.$nextTick(function(){}),so,今天就专门研究研究到底是怎么一回事:

this.$nextTick 一般在created钩子函数中使用,有人会问,在created 和 mounted 钩子函数中使用有什么区别呢?

这就要回到vue的生命周期了:

  1.    beforeCreated :    初始化Vue,此时 data 和 el 并未被创建
    
  2.        created:     data被初始化但是el并未被创建
    
  3.    beforeMounted:     data 和 el  都被创建,但是还未被挂载 
    
  4.      mounted:     data  和 el 都被创建,并且被挂载
    

在created 钩子函数中,数据初始化了但是页面并没有更新,而 $nextTick 是异步行为,在数据变化的同时,页面也会同步;

在mounted钩子函数中,由于页面已经加载完了,所以不需要异步操作。但是写了也不会错。。

下面看一个例子,进一步说明 $nextTick 的作用:

<div class="app">
  <div ref="msgDiv">{{msg}}</div>
  <div v-if="msg1">Message got outside $nextTick: {{msg1}}</div>
  <div v-if="msg2">Message got inside $nextTick: {{msg2}}</div>
  <div v-if="msg3">Message got outside $nextTick: {{msg3}}</div>
  <button @click="changeMsg">
    Change the Message
  </button>
</div>
new Vue({
  el: '.app',
  data: {
    msg: 'Hello Vue.',
    msg1: '',
    msg2: '',
    msg3: ''
  },
  methods: {
    changeMsg() {
      this.msg = "Hello world."
      this.msg1 = this.$refs.msgDiv.innerHTML
      this.$nextTick(() => {
        this.msg2 = this.$refs.msgDiv.innerHTML
      })
      this.msg3 = this.$refs.msgDiv.innerHTML
    }
  }
})

点击前:


image.png

点击后:


image.png

最后nwxtTick的应用场景有哪些呢?

1.在Vue生命周期的created()钩子函数进行的DOM操作一定要放在Vue.nextTick()的回调函数中

2.在数据变化后要执行的某个操作,而这个操作需要使用随数据改变而改变的DOM结构的时候,这个操作都应该放进Vue.nextTick()的回调函数中。

相关文章

网友评论

      本文标题:vue基础--this.$nextTick(function()

      本文链接:https://www.haomeiwen.com/subject/xwuusktx.html