惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Vercel News
Vercel News
O
OpenAI News
Engineering at Meta
Engineering at Meta
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
月光博客
月光博客
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
WordPress大学
WordPress大学
宝玉的分享
宝玉的分享
GbyAI
GbyAI
T
The Blog of Author Tim Ferriss
Google DeepMind News
Google DeepMind News
B
Blog RSS Feed
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
云风的 BLOG
云风的 BLOG
罗磊的独立博客
S
SegmentFault 最新的问题
The Register - Security
The Register - Security
Hugging Face - Blog
Hugging Face - Blog
D
DataBreaches.Net
U
Unit 42
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
B
Blog
阮一峰的网络日志
阮一峰的网络日志
P
Proofpoint News Feed
雷峰网
雷峰网
V
Visual Studio Blog
小众软件
小众软件
aimingoo的专栏
aimingoo的专栏
N
Netflix TechBlog - Medium
酷 壳 – CoolShell
酷 壳 – CoolShell
H
Hackread – Cybersecurity News, Data Breaches, AI and More
Y
Y Combinator Blog
博客园 - 【当耐特】
G
Google Developers Blog
L
LangChain Blog
Stack Overflow Blog
Stack Overflow Blog
I
InfoQ
Martin Fowler
Martin Fowler
F
Fortinet All Blogs
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
The Cloudflare Blog
AI
AI
Google Online Security Blog
Google Online Security Blog
Hacker News - Newest:
Hacker News - Newest: "LLM"
博客园 - Franky
Blog — PlanetScale
Blog — PlanetScale
Webroot Blog
Webroot Blog
PCI Perspectives
PCI Perspectives
爱范儿
爱范儿
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org

Dmitri Pavlutin Blog

Pure Functions in JavaScript: A Beginner's Guide Record Type in TypeScript: A Quick Intro How to Write Comments in React: The Good, the Bad and the Ugly 4 Ways to Create an Enum in JavaScript React forwardRef(): How to Pass Refs to Child Components TypeScript Function Types: A Beginner's Guide How to Use v-model to Access Input Values in Vue Mastering Vue refs: From Zero to Hero Environment Variables in JavaScript: process.env 5 Must-Know Differences Between ref() and reactive() in Vue How to Destructure Props in Vue (Composition API) Triangulation in Test-Driven Development Programming to Interface Vs to Implementation A Smarter JavaScript Mapper: array.flatMap() Array Grouping in JavaScript: Object.groupBy() How to Access ES Module Metadata using import.meta JSON Modules in JavaScript How to Trim Strings in JavaScript TypeScript Function Overloading How to Debounce and Throttle Callbacks in Vue How to Show/Hide Elements in Vue Sparse vs Dense Arrays in JavaScript How to Fill an Array with Initial Values in JavaScript Covariance and Contravariance in TypeScript What are Higher-Order Functions in JavaScript? How to Use TypeScript with React Components Index Signatures in TypeScript How to Use React useReducer() Hook unknown vs any in TypeScript A Guide to React Context and useContext() Hook How to Use Promise.any() 2 Ways to Remove a Property from an Object in JavaScript 'return await promise' vs 'return promise' in JavaScript How to Use Promise.allSettled() How to Use fetch() with JSON JavaScript Promises: then(f,f) vs then(f).catch(f) What is a Promise in JavaScript? How to Use Promise.all() A Simple Guide to Component Props in React Don't Stop Me Now: How to Use React useTransition() hook A Simple Explanation of JavaScript Variables: const, let, var ES Modules Dynamic Import How to Memoize with React.useMemo() How to Cleanup Async Effects in React Why Math.max() Without Arguments Returns -Infinity How to Debounce and Throttle Callbacks in React Don't Confuse Function Expressions and Function Declarations in JavaScript How to Use ES Modules in Node.js Solving a Mystery Behavior of parseInt() in JavaScript How to Use Array Reduce Method in JavaScript 3 Ways to Merge Arrays in JavaScript A Guide to Jotai: the Minimalist React State Management Library The Difference Between Values and References in JavaScript How to Implement a Queue in JavaScript A Helpful Algorithm to Determine "this" value in JavaScript React useRef() Hook Explained in 3 Steps 7 Interview Questions on "this" keyword in JavaScript. Can You Answer Them? How to Greatly Enhance fetch() with the Decorator Pattern 7 Interview Questions on JavaScript Closures. Can You Answer Them? What's a Method in JavaScript? array.sort() Does Not Simply Sort Numbers in JavaScript How to Solve the Infinite Loop of React.useEffect() The New Array Method You'll Enjoy: array.at(index) What's the Difference between DOM Node and Element? Why Promises Are Faster Than setTimeout()? Everything About Callback Functions in JavaScript How React Updates State 5 Mistakes to Avoid When Using React Hooks 5 Best Practices to Write Quality JavaScript Variables Type checking in JavaScript: typeof and instanceof operators 3 Ways to Check if a Variable is Defined in JavaScript React Forms Tutorial: Access Input Values, Validate, Submit Forms Prototypal Inheritance in JavaScript How to Timeout a fetch() Request How to Learn JavaScript If You're a Beginner A Simple Explanation of React.useEffect() A Simple Explanation of JavaScript Iterators How to Use React Controlled Inputs Everything about null in JavaScript How to Use Fetch with async/await Getting Started with Arrow Functions in JavaScript An Interesting Explanation of async/await in JavaScript Front-end Architecture: Stable and Volatile Dependencies Is it Safe to Compare JavaScript Strings? How to Access Object's Keys, Values, and Entries in JavaScript What Actually is a String in JavaScript? 3 Ways to Shallow Clone Objects in JavaScript (w/ bonuses) Checking if an Array Contains a Value in JavaScript JavaScript Event Delegation: A Beginner's Guide How to Parse URL in JavaScript: hostname, pathname, query, hash 3 Ways to Detect an Array in JavaScript How to Get the Screen, Window, and Web Page Sizes in JavaScript 3 Ways to Check If an Object Has a Property/Key in JavaScript How to Compare Objects in JavaScript Object.is() vs Strict Equality Operator in JavaScript Own and Inherited Properties in JavaScript 5 Differences Between Arrow and Regular Functions How to Use Object Destructuring in JavaScript Your Guide to React.useCallback() 5 JavaScript Scope Gotchas
How to Use nextTick() in Vue
Dmitri Pavlutin · 2022-02-12 · via Dmitri Pavlutin Blog
Post cover

A change to Vue component's data (props or state) isn't immediately reflected in the DOM. Rather, Vue updates DOM asynchronously.

You can catch the moment when Vue updates DOM using Vue.nextTick() or vm.$nextTick() functions. Let's see in detail how these functions work.

1. nextTick()

As Vue component data changes, the DOM is updated asynchronously. Vue collects multiple updates to virtual DOM from all the components, and then creates a single batch to update the DOM.

Updating DOM in a single batch is more performant than doing multiple small updates.

For example, let's consider a component that toggles the display of an element:


<script setup>

import { ref } from 'vue'

const show = ref(true)

const content = ref()

const handleClick = () => {

show.value = !show.value

console.log(show.value, content.value)

}

</script>

<template>

<div>

<button @click="handleClick">Insert/Remove</button>

<div v-if="show" ref="content">I am an element</div>

</div>

</template>


Open the demo.

Clicking on "Insert/Remove" button changes show flag, which toggles the display of <div id="content"> element using v-if="show" directive.

Looking into handleClick, right after data mutation show.value = !show.value, the logged DOM data doesn't correspond to show value. If show is true, then content is null: which means that DOM is not in sync with the component's data.

If you want to catch the moment when DOM has just been updated, then you need to use a special function nextTick(callback). It executes callback after the new data updates have reached DOM.

Let's find the moment when the <div> element is inserted or removed from the DOM:


<script setup>

import { ref, nextTick } from 'vue'

const show = ref(true)

const content = ref()

const handleClick = () => {

show.value = !show.value

nextTick(() => {

console.log(show.value, content.value)

})

}

</script>

<template>

<div>

<button @click="handleClick">Insert/Remove</button>

<div v-if="show" ref="content">I am an element</div>

</div>

</template>


Open the demo.

Open the demo and click a few times the Insert/Remove button. You'd see that content (the reference that contains the <div> element) is null or contains an element in exact correspondence with show value.

Also, nextTick(callback) executes the callback when all children components updates have been submitted to DOM.

There's also this.$nextTick(callback) available on the component instance, which you might find useful in the case of options API.

2. nextTick() with async/await

If nextTick() is called without arguments, it will return a promise that resolves when component data changes reach DOM.

This helps to take advantage of the more readable async/await syntax.

For example, let's make the previous component more readable by catching the DOM update with the async/await syntax:


<script setup>

import { ref, nextTick } from 'vue'

const show = ref(true)

const content = ref()

const handleClick = async () => {

show.value = !show.value

await nextTick()

console.log(show.value, content.value)

}

</script>

<template>

<div>

<button @click="handleClick">Insert/Remove</button>

<div v-if="show" ref="content">I am an element</div>

</div>

</template>


Open the demo.

const handleClick = async () => {...} has been marked as an asynchronous function.

When the Insert/Remove button is clicked, the value of show changes.

await nextTick() awaits until the changes reach DOM. Finally, console.log(content) logs the actual content of the reference.

My recommendation is to use the nextTick() with the async/await syntax, as it's more readable than the callback approach.

3. Conclusion

When you change the component's data, Vue updates the DOM asynchronously.

If you want to catch the moment when DOM has been updated after the component's data change, then you need to use nextTick(callback) or this.$nextTick(callback) (options API) functions.

Their single callback argument is invoked right after DOM update: and you are guaranteed to get the latest DOM in sync with the component's data.

Alternatively, if you don't pass the callback argument to nextTick(): the functions will return a promise that'll be resolved when DOM is updated.

I recommend using nextTick() with async/await syntax for better readability.

Dmitri Pavlutin

About Dmitri Pavlutin

Software developer and sometimes writer. My daily routine consists of (but not limited to) drinking coffee, coding, writing, overcoming boredom 😉, developing a gift boxes Shopify app, and blogging about Shopify. Living in the sunny Barcelona. 🇪🇸