nextTick() in vue3

nextTick() method

The nextTick() method is a very powerful tool, a tool method that waits for the next DOM update refresh. Used to asynchronously defer execution of a function until the next DOM update cycle.

When we change the responsive state in Vue, the final DOM updates are not synchronized, but Vue caches them in a queue until the next "tick". This is to ensure that each component is only updated once, no matter how many state changes occur.

nextTick() can be used immediately after a state change, and it accepts a callback function as an argument that will be executed at the end of the DOM update cycle. The nextTick() method can postpone the asynchronous operation until the next DOM update cycle, thus ensuring that the updated DOM is correctly obtained after the data changes.

In vue3, nextTick() is a Promise object, so we can also use the Promise returned by await.

usage

Using the callback function

In Vue 3, we can implement the call of the nextTick() method through $nextTick() the method . The $nextTick() method is an instance method provided by Vue 3 that can be used to perform asynchronous operations in components. Here is a simple example using the nextTick() method:

export default {
    
    
  data() {
    
    
    return {
    
    
      name: "Vue 3"
    };
  },
  methods: {
    
    
    showName() {
    
    
      console.log(this.$el.innerHTML);   // 'Vue 3'
    },
    updateName() {
    
    
      this.name = "Vue 4";
      this.$nextTick(this.showName);
    }
  }
}

In the above code, we define a component, and define a data attribute name in it, and two methods showName and updateName. The showName method is used to print the innerHTML of the component, the updateName method is used to modify the value of the name attribute, and the showName method is called through $nextTick()the method . The purpose of this is to ensure that the updated DOM is obtained after the modification is completed.

await way to use

export default {
    
    
  data() {
    
    
    return {
    
    
      name: "Vue 3"
    };
  },
  methods: {
    
    
    showName() {
    
    
      console.log(this.$el.innerHTML);   // 'Vue 3'
    },
   async updateName() {
    
    
      this.name = "Vue 4";
      await this.$nextTick(); 
      this.showName(); 
    }
  }
}

Realization principle

In Vue3, when we make a change to a component's state, we actually add it to an update queue, and all changes in that queue are applied to the DOM on the next "update cycle". This behavior is called asynchronous update.

The nextTick() method provides a good opportunity to access the updated DOM after a component state change.

The nextTick() method in Vue3 is implemented by wrapping the callback between a Promise and a microtask queue. A microtask is a task that executes as soon as the current task completes, and Promise's then() is a way to perform asynchronous operations without blocking the main thread. The resolve() method of Promise is a Promise that produces a success status, which can be used to wrap a microtask queue and add a new task at the end of the queue.

The sample code of the implementation principle of the nextTick() method is as follows:

let callbacks = [] // 存储回调函数的数组
let pending = false // 标记是否有待处理的任务

// 执行任务队列的函数
const flushCallbacks = () => {
    
    
  // 标记为 "待处理任务" 的任务已处理
  pending = false 
  
  // 复制回调函数数组并清空当前数组,以防回调函数在执行期间被添加
  const copies = callbacks.slice(0)
  callbacks = []
  
  // 依次执行每个回调函数
  for (let i = 0; i < copies.length; i++) {
    
    
    copies[i]()
  }
}

// 添加任务到任务队列的函数
const nextTick = (cb) => {
    
    
  callbacks.push(cb) // 将回调函数添加到待处理任务的数组中
  if (!pending) {
    
     // 如果当前没有待处理任务,则标记为待处理
    pending = true
    Promise.resolve().then(flushCallbacks) // 创建 Promise,并加入到微任务队列中,then()中执行 flushCallbacks() 函数
  }
}

When using, we directly call the nextTick() method

nextTick(() => {
    
    
    // 在DOM更新后执行回调函数
    console.log('DOM updated!')
})

Changes added in the update queue will be processed in the next "update cycle", during which Vue3 applies the changes to the DOM, so when the nextTick() callback is executed, the latest DOM state is visible. Queuing the callback, rather than adding it immediately to the microtask queue, improves performance by avoiding repeated calls to the callback in the same common situations.

Considerations when using the nextTick() method

When using the nextTick() method, you need to pay attention to the following points:

  • Do not rely too much on the nextTick() method as it will reduce the readability and maintainability of the code.
  • The nextTick() method is to execute the callback function at the end of the next DOM update cycle, so the callback function may have a certain delay.
  • When using the nextTick() method, you need to ensure that the callback function does not modify the DOM multiple times to avoid affecting performance.
  • Avoid callback hell: If callback functions are nested too many layers, the code may become unmaintainable.
  • Use the nextTick() method appropriately: Use the nextTick() method only when you need to execute a callback function after the DOM has been updated.

The nextTick() method is a very powerful method. We will often use it in the development process, but we should pay attention to the above points when using it to avoid abuse and cause performance degradation.

Well, this is the end of the chat about the use of the nextTick() method. If you like it, like it, follow it and add a favorite!

Guess you like

Origin blog.csdn.net/w137160164/article/details/131137194