Home > Web Front-end > Vue.js > body text

Detailed explanation of nextTick function in Vue3: processing operations after DOM update

WBOY
Release: 2023-06-18 09:30:07
Original
17555 people have browsed it

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>
Copy after login
  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>
Copy after login

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)
}
Copy after login

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())
  }
}
Copy after login

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>
Copy after login

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>
Copy after login

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>
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!