search
HomeWeb Front-endVue.jsDetailed explanation of nextTick function in Vue3: processing operations after DOM update

With the rapid development of front-end technology, modern front-end frameworks emerge in endlessly, and Vue.js is one of the best. Vue.js is a progressive JavaScript framework that is easy to learn, efficient, and flexible, making it ideal for building interactive web interfaces. Vue.js 3 is the latest version of Vue.js. It further improves the superiority of Vue.js through a series of continuous performance improvements, architectural reconstruction, and improved development experience. Among them, the nextTick function is a feature in Vue.js 3 that deserves further exploration.

This article will give you a detailed introduction to the nextTick function in Vue.js 3, including its basic usage, implementation principles and application scenarios.

1. Basic usage of nextTick function

The nextTick function in Vue.js is an asynchronous method used to perform some specific operations after the DOM is updated. It is executed in a micro-task manner, that is, in the same event loop, all synchronization tasks are executed immediately after completion. This will ensure that the callback called by nextTick is executed after the actual DOM update, which is very important if we are operating after the DOM has been updated.

In Vue.js 3, the following functions can be achieved by using the nextTick function:

  1. Manipulate the DOM immediately after the data is modified

Because Vue. js uses an asynchronous update strategy, so after the data is modified, the DOM will not be updated immediately, but will wait for the next update of Vue.js to be re-rendered. If we need to operate the DOM immediately after the data is modified, we can use the nextTick function.

For example, we use the v-if directive in the template to achieve an effect of showing/hiding content. When we need to change the DOM style according to data changes, we can use the nextTick function to achieve this.

<template> 
  <div>
    <button @click="toggleContent">切换内容显示</button>
    <div v-if="showContent" ref="content">这是要显示的内容</div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      showContent: false
    }
  },
  methods: {
    toggleContent() {
      this.showContent = !this.showContent
      this.$nextTick(() => {
        // 在DOM更新后,修改样式
        this.$refs.content.style.color = 'red'
      })
    }
  }
}
</script>
  1. Get the updated DOM information

When the data is updated and we need to get the updated DOM information, we can use the nextTick function. Because the nextTick function will be executed after the real DOM is updated, we can obtain the updated DOM information.

For example, we use the v-for instruction in the template to traverse an array, and then obtain the style information of the li element after the DOM is updated.

<template>
  <div>
    <ul>
      <li v-for="item in list" :key="item">{{ item }}</li>
    </ul>
    <button @click="getListStyle">获取列表样式</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      list: ['item1', 'item2', 'item3']
    }
  },
  methods: {
    getListStyle() {
      this.list.push('item4')
      this.$nextTick(() => {
        // 获取更新后的li元素样式信息
        const liList = document.querySelectorAll('li')
        liList.forEach((li) => {
          console.log(li.style)
        })
      })
    }
  }
}
</script>

2. Implementation principle of nextTick function

In Vue.js 3, there are two main ways to implement nextTick function: using Promise and using MutationObserver.

  1. Using Promise

In Vue.js 3, use Promise to encapsulate the nextTick function. The specific process is as follows:

// 初始化Promise
const promise = Promise.resolve()

export function nextTick(callback?: Function) {
  // 将回调包装成一个微任务函数
  return promise.then(callback)
}

In the above code, Promise.resolve() is used to initialize a Promise object, then return a new Promise object, and register a callback function callback in the then() method. Because Promise is a microtask, the callback function in the nextTick function is also a microtask, which is more efficient than setTimeout or setImmediate.

  1. Using MutationObserver

MutationObserver is an asynchronous API that comes with the browser, which can be used to monitor changes in the DOM tree to achieve asynchronous operations.

In Vue.js 3, the nextTick function can be encapsulated through MutationObserver. The specific process is as follows:

const callbacks = []
let pending = false

// 回调函数
function flushCallbacks() {
  // 标记异步任务已经在执行
  pending = false
  // 执行回调函数
  const copies = callbacks.slice(0)
  callbacks.length = 0
  for (let i = 0; i < copies.length; i++) {
    copies[i]()
  }
}

// 创建Observer实例
const observer = new MutationObserver(flushCallbacks)

// 注册用户行为
const textNode = document.createTextNode(String(0))
observer.observe(textNode, {
  characterData: true
})

export function nextTick(callback?: Function) {
  callbacks.push(() => {
    if (callback) {
      try {
        callback()
      } catch (e) {
        console.error(e)
      }
    }
  })

  if (!pending) {
    // 标记异步任务未执行
    pending = true
    // 改变textNode的值
    textNode.data = String(Date.now())
  }
}

In the above code, an Observer instance is created using MutationObserver, and then a textNode node is registered to listen for changes in characterData. When the data attribute of textNode changes, the flushCallbacks() method will be executed. In nextTick, we put the callback function callback into the callbacks array, then change the data attribute of textNode, trigger the characterData change event of MutationObserver, thereby executing the flushCallbacks() method and executing all callback functions.

3. Application scenarios of nextTick function

The nextTick function in Vue.js has many application scenarios, and only a few of them are introduced here.

  1. Operation DOM in the v-for instruction

When using the v-for instruction to traverse the array, if you need to operate on all DOM elements, you can use nextTick.

<template>
  <div>
    <ul>
      <li v-for="item in list" :key="item">{{ item }}</li>
    </ul>
  </div>
</template>

<script>
export default {
  data() {
    return {
      list: ['item1', 'item2', 'item3']
    }
  },
  methods: {
    operateDOM() {
      this.$nextTick(() => {
        // 操作所有的li元素
        const liList = document.querySelectorAll('li')
        liList.forEach((li, index) => {
          li.style.color = `hsl(${index * 50}, 70%, 50%)`
        })
      })
    }
  }
}
</script>

In the code, after the v-for instruction updates the DOM, use the nextTick function to operate all li elements and set their color values.

  1. Operation DOM after asynchronous data update

After asynchronously updating data, if you need to operate the updated DOM, you can also use nextTick.

<template>
  <div>
    <p>{{ message }}</p>
    <button @click="changeMessage">异步更改message</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      message: 'Hello Vue.js'
    }
  },
  methods: {
    changeMessage() {
      setTimeout(() => {
        this.message = 'Hello World'
        this.$nextTick(() => {
          // 操作更新后的DOM
          document.querySelector('p').style.color = 'red'
        })
      }, 1000)
    }
  }
}
</script>

In the code, after updating the data asynchronously, use setTimeout to delay for 1 second, and then update the value of message. After the message value is updated, use the nextTick function to operate the updated DOM and set the color of the p element to red.

  1. Dynamicly add DOM nodes

When dynamically adding DOM nodes, if you need to operate the newly added DOM nodes, you can also use nextTick.

<template>
  <div>
    <ul ref="list">
      <li v-for="item in list" :key="item">{{ item }}</li>
    </ul>
    <button @click="addItem">动态添加一项</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      list: ['item1', 'item2', 'item3']
    }
  },
  methods: {
    addItem() {
      this.list.push('item4')
      this.$nextTick(() => {
        // 操作新加入的li元素
        const liList = this.$refs.list.querySelectorAll('li')
        liList[liList.length - 1].style.color = 'red'
      })
    }
  }
}
</script>

In the code, the v-for instruction is used to traverse the array, and then an item is dynamically added when the button is clicked. After the addition is completed, use the nextTick function to operate the newly added li elements and set their color to red.

4. Summary

In Vue.js 3, the nextTick function is a very practical feature. It can perform some specific operations after the DOM is updated, such as modifying the DOM style and obtaining updates. The final DOM information, etc. There are two main ways to implement the nextTick function: using Promise and using MutationObserver. In actual development, according to different application scenarios, we can flexibly use the nextTick function to improve development efficiency and user experience.

The above is the detailed content of Detailed explanation of nextTick function in Vue3: processing operations after DOM update. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Vue常见面试题汇总(附答案解析)Vue常见面试题汇总(附答案解析)Apr 08, 2021 pm 07:54 PM

本篇文章给大家分享一些Vue面试题(附答案解析)。有一定的参考价值,有需要的朋友可以参考一下,希望对大家有所帮助。

5 款适合国内使用的 Vue 移动端 UI 组件库5 款适合国内使用的 Vue 移动端 UI 组件库May 05, 2022 pm 09:11 PM

本篇文章给大家分享5 款适合国内使用的 Vue 移动端 UI 组件库,希望对大家有所帮助!

vue中props可以传递函数吗vue中props可以传递函数吗Jun 16, 2022 am 10:39 AM

vue中props可以传递函数;vue中可以将字符串、数组、数字和对象作为props传递,props主要用于组件的传值,目的为了接收外面传过来的数据,语法为“export default {methods: {myFunction() {// ...}}};”。

手把手带你利用vue3.x绘制流程图手把手带你利用vue3.x绘制流程图Jun 08, 2022 am 11:57 AM

利用vue3.x怎么绘制流程图?下面本篇文章给大家分享基于 vue3.x 的流程图绘制方法,希望对大家有所帮助!

聊聊vue指令中的修饰符,常用事件修饰符总结聊聊vue指令中的修饰符,常用事件修饰符总结May 09, 2022 am 11:07 AM

本篇文章带大家聊聊vue指令中的修饰符,对比一下vue中的指令修饰符和dom事件中的event对象,介绍一下常用的事件修饰符,希望对大家有所帮助!

如何覆盖组件库样式?React和Vue项目的解决方法浅析如何覆盖组件库样式?React和Vue项目的解决方法浅析May 16, 2022 am 11:15 AM

如何覆盖组件库样式?下面本篇文章给大家介绍一下React和Vue项目中优雅地覆盖组件库样式的方法,希望对大家有所帮助!

通过9个Vue3 组件库,看看聊前端的流行趋势!通过9个Vue3 组件库,看看聊前端的流行趋势!May 07, 2022 am 11:31 AM

本篇文章给大家分享9个开源的 Vue3 组件库,通过它们聊聊发现的前端的流行趋势,希望对大家有所帮助!

react与vue的虚拟dom有什么区别react与vue的虚拟dom有什么区别Apr 22, 2022 am 11:11 AM

react与vue的虚拟dom没有区别;react和vue的虚拟dom都是用js对象来模拟真实DOM,用虚拟DOM的diff来最小化更新真实DOM,可以减小不必要的性能损耗,按颗粒度分为不同的类型比较同层级dom节点,进行增、删、移的操作。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools