• Vue之nextTick


    例子

    <template>
      <div id="app">
    <!--    <hello-world />-->
        <div ref="msg">{{ msg }}</div>
        <button @click="change">change</button>
      </div>
    </template>
    
    <script>
    // import HelloWorld from './components/HelloWorld/index'
    export default {
      name: 'App',
      components: {
        // HelloWorld
      },
      data() {
        return {
          msg: 'hello world',
        };
      },
      methods: {
        change() {
          this.$nextTick(() => {
            console.log('nextTick:',this.$refs.msg.innerText);
          });

        this.$nextTick().then(() => { console.log('nextTick with promise:',this.$refs.msg.innerText); }); this.msg = 'hello vue'; }, } } </script>
    • 当点击change时,会执行Vue源码中的nextTick方法,该方法把将要执行的任务推入到一个队列中,在下一个tick时,同步执行。
    • 当源码走第一次执行nextTick方法时,会把this.$nextTikc回到放到一个callbacks数组里,也就是会在任务队里添加一个异步任务,当走到this.$nextTick().then()时,向队列添加异步任务时,也返回了一个异步任务Promise,在then方法中会执行flushCallbacks回调,然后再执行我们自己写的Promise回调,继续走到this.msg = 'hello vue'时,也会添加一个异步任务(flushSchedulerQueue),这个异步任务里会执行getter,数据更新与重新渲染等。
    • 依次执行callbacks数组里的任务,首先会执行第一个任务,也就是this.$nextTick,此时数据还没变化,所以输出'nextTick:hello world',然后执行this.$nextTick().then(),此时该方法在源码里会返回一个Pomise,然后再then方法执行它,所以它会在callbacks三个任务执行完后,最后执行它,继续执行,执行flushSchedulerQueue函数进行数据变化执行getter,数据更新最后更新渲染页面,该函数执行完成后,此时页面已经刷新,数据变成hello vue,最后执行this.$nextTick().then(),此时打印出'nextTick with promise:hello vue'

    下一个 tick 的意思是说当前的执行栈为空,去拿宏任务或者是微任务,那么就可以叫做下一个 tick。如果是基于微任务实现的 nextTick,nextTick 就是在微任务执行阶段执行,不是下一次事件循环。当前 Tick 就是当前宏任务执行阶段,nextTick 就是接下来的微任务执行阶段。

  • 相关阅读:
    从零开始入门 K8s | 应用编排与管理
    209. Minimum Size Subarray Sum
    208. Implement Trie (Prefix Tree)
    207. Course Schedule
    203. Remove Linked List Elements
    183. Customers Who Never Order
    182. Duplicate Emails
    181. Employees Earning More Than Their Managers
    1261. Find Elements in a Contaminated Binary Tree
    1260. Shift 2D Grid
  • 原文地址:https://www.cnblogs.com/ltog/p/14442062.html
Copyright © 2020-2023  润新知